Edgewall Software

Ticket #9536: 9536-and-or-if-else-2-r10590.patch

File 9536-and-or-if-else-2-r10590.patch, 87.1 KB (added by rblank, 15 months ago)

Second (and final) "and or → if else" batch.

  • trac/search/templates/search.html

    diff --git a/trac/search/templates/search.html b/trac/search/templates/search.html
    a b  
    3030        <p class="filters"> 
    3131          <py:for each="filter in filters"> 
    3232            <input type="checkbox" id="${filter.name}" name="${filter.name}" 
    33                    checked="${'checked' if filter.active else None}" /> 
     33                   checked="${filter.active or None}" /> 
    3434            <label for="${filter.name}">${filter.label}</label> 
    3535          </py:for> 
    3636       </p> 
  • trac/ticket/notification.py

    diff --git a/trac/ticket/notification.py b/trac/ticket/notification.py
    a b class TicketNotifyEmail(NotifyEmail): 
    8484        ambiguous_char_width = env.config.get('notification', 
    8585                                              'ambiguous_char_width', 
    8686                                              'single') 
    87         self.ambiwidth = (1, 2)[ambiguous_char_width == 'double'] 
     87        self.ambiwidth = 2 if ambiguous_char_width == 'double' else 1 
    8888 
    8989    def notify(self, ticket, newticket=True, modtime=None): 
    9090        """Send ticket change notification e-mail (untranslated)""" 
  • trac/ticket/query.py

    diff --git a/trac/ticket/query.py b/trac/ticket/query.py
    a b class QueryModule(Component): 
    940940                     conversion[1], conversion[4], conversion[0]) 
    941941 
    942942        if format: 
    943             filename = ('query', None)[format == 'rss'] 
     943            filename = 'query' if format != 'rss' else None 
    944944            Mimeview(self.env).send_converted(req, 'trac.ticket.Query', query, 
    945945                                              format, filename=filename) 
    946946 
  • trac/ticket/templates/query.html

    diff --git a/trac/ticket/templates/query.html b/trac/ticket/templates/query.html
    a b  
    4040          <table summary="Query filters"> 
    4141            <tbody py:for="clause_num, constraints in enumerate(clauses or [{}])" 
    4242                   py:with="clause_pre = '%d_' % clause_num"> 
    43               <tr style="${clause_num == 0 and 'display: none' or None}"> 
     43              <tr style="${'display: none' if clause_num == 0 else None}"> 
    4444                <td> 
    4545                  <div class="trac-clause-lsep">&nbsp;<hr /></div> 
    4646                  <div class="trac-clause-msep">Or</div> 
     
    6666                          <td py:if="field.type not in ('radio', 'checkbox', 'time')" class="mode"> 
    6767                            <select name="${n_field_name}_mode"> 
    6868                              <option py:for="mode in modes[field.type]" value="$mode.value" 
    69                                 selected="${mode.value == constraint.mode and 'selected' or None}">$mode.name</option> 
     69                                      selected="${mode.value == constraint.mode or None}">$mode.name</option> 
    7070                            </select> 
    7171                          </td> 
    7272                        </py:when> 
    7373                        <py:otherwise><!--! not the first line of a multiline constraint --> 
    74                           <th colspan="${field.type == 'time' and 1 or 2}"><label>or</label></th> 
     74                          <th colspan="${1 if field.type == 'time' else 2}"><label>or</label></th> 
    7575                        </py:otherwise> 
    7676                      </py:choose> 
    7777 
    78                       <td class="filter" colspan="${field.type in ('radio', 'checkbox', 'time') and 2 or None}" 
     78                      <td class="filter" colspan="${2 if field.type in ('radio', 'checkbox', 'time') else None}" 
    7979                          py:choose=""> 
    8080 
    8181                        <py:when test="field.type == 'select'"> 
     
    9898                          <py:for each="option in field.options"> 
    9999                            <input type="checkbox" id="_${n_field_name}_$option" name="${n_field_name}" 
    100100                              value="$option" 
    101                               checked="${((constraint['mode'] == '') == (option in constraint['values'])) 
    102                                        and 'checked' or None}" /> 
     101                              checked="${((constraint['mode'] == '') == (option in constraint['values'])) or None}" /> 
    103102                            <label for="_${n_field_name}_$option" class="control">${option or 'none'}</label> 
    104103                          </py:for> 
    105104                        </py:when> 
     
    172171            <py:for each="column in all_columns"> 
    173172              <label> 
    174173                <input type="checkbox" name="col" value="$column" 
    175                        checked="${any([(value == column) for value in col]) 
    176                                   and 'checked' or None}" /> 
     174                       checked="${any(value == column for value in col) or None}" /> 
    177175                ${fields.get(column, {'label': column or 'none'}).label} 
    178176              </label> 
    179177            </py:for> 
     
    200198          Show under each result: 
    201199          <py:for each="column in all_textareas"> 
    202200            <label><input type="checkbox" name="row" value="$column" 
    203                 checked="${any([(value == column) for value in row]) and 'checked' or None}" /> 
     201                          checked="${any(value == column for value in row) or None}" /> 
    204202            ${fields.get(column, {'label': column or 'none'}).label}</label> 
    205203          </py:for> 
    206204        </p> 
     
    233231                   value="${_('Edit query')}" /> 
    234232          </div> 
    235233        </form> 
    236         <form py:if="new or edit" method="get" action="${edit and url_of(report_resource) or href.report()}"> 
     234        <form py:if="new or edit" method="get" action="${url_of(report_resource) if edit else href.report()}"> 
    237235          <div> 
    238             <input type="hidden" name="action" value="${edit and 'edit' or 'new'}" /> 
     236            <input type="hidden" name="action" value="${'edit' if edit else 'new'}" /> 
    239237            <input type="hidden" name="query" value="${query.to_string()}" /> 
    240238            <input type="submit" value="${_('Save query')}" 
    241                    title="${edit and _('Save updated query in report {%(id)s}', id=report_resource.id) or 
    242                                     _('Create new report from current query')}" /> 
     239                   title="${_('Save updated query in report {%(id)s}', id=report_resource.id) if edit 
     240                            else _('Create new report from current query')}" /> 
    243241          </div> 
    244242        </form> 
    245243        <form py:if="delete" method="get" action="${url_of(report_resource)}"> 
  • trac/ticket/templates/query_results.html

    diff --git a/trac/ticket/templates/query_results.html b/trac/ticket/templates/query_results.html
    a b  
    3333  <py:def function="column_headers()"> 
    3434    <tr class="trac-columns"> 
    3535      <th py:for="header in headers" 
    36           class="$header.name${query.order == header.name and (query.desc and ' desc' or ' asc') or ''}"> 
     36          class="$header.name${(' desc' if query.desc else ' asc') if query.order == header.name else ''}"> 
    3737        <?python asc = _('(ascending)'); desc = _('(descending)') ?> 
    3838        <a title="${_('Sort by %(col)s %(direction)s', col=header.label, 
    39                       direction=(query.order == header.name and not query.desc and desc or asc))}" 
     39                      direction=(desc if query.order == header.name and not query.desc else asc))}" 
    4040           href="$header.href">${header.label}</a> 
    4141      </th> 
    4242    </tr> 
    4343  </py:def> 
    44   ${groups and group_heading(*groups[0]) or None} 
     44  ${group_heading(*groups[0]) if groups else None} 
    4545  <table class="listing tickets"> 
    4646    <thead py:strip="group_index"> 
    4747      ${column_headers()} 
     
    6565          <py:with vars="ticket_context = context.child('ticket', result.id)"> 
    6666            <py:if test="'TICKET_VIEW' in perm(ticket_context.resource)"> 
    6767 
    68               <tr class="${idx % 2 and 'odd' or 'even'} prio${result.priority_value}${ 
    69                 'added' in result and ' added' or ''}${ 
    70                 'changed' in result and ' changed' or ''}${ 
    71                 'removed' in result and ' removed' or ''}"> 
     68              <tr class="${'odd' if idx % 2 else 'even'} prio${result.priority_value}${ 
     69                ' added' if 'added' in result else ''}${ 
     70                ' changed' if 'changed' in result else ''}${ 
     71                ' removed' if 'removed' in result else ''}"> 
    7272                <py:for each="idx, header in enumerate(headers)" py:choose=""> 
    7373                  <py:with vars="name = header.name; value = result[name]"> 
    7474                    <td py:when="name == 'id'" class="id"><a href="$result.href" title="View ticket" 
  • trac/ticket/templates/report.rss

    diff --git a/trac/ticket/templates/report.rss b/trac/ticket/templates/report.rss
    a b  
    1010    <image py:if="chrome.logo.src_abs"> 
    1111      <title>$project.name</title> 
    1212      <url>$chrome.logo.src_abs</url> 
    13       <link>${abs_href.report(report.id != -1 and report.id or '')}</link> 
     13      <link>${abs_href.report(report.id if report.id != -1 else '')}</link> 
    1414    </image> 
    1515    <generator>Trac v${trac.version}</generator> 
    1616 
  • trac/ticket/templates/report_edit.html

    diff --git a/trac/ticket/templates/report_edit.html b/trac/ticket/templates/report_edit.html
    a b  
    1313  <body> 
    1414    <div id="content" class="report"> 
    1515 
    16       <h1>${action == 'new' and _('New Report') or report.title}</h1> 
     16      <h1>${_('New Report') if action == 'new' else report.title}</h1> 
    1717      <form action="${href.report(report.id)}" method="post" id="edit_report"> 
    1818        <div> 
    1919          <input type="hidden" name="action" value="$action" /> 
  • trac/ticket/templates/report_list.html

    diff --git a/trac/ticket/templates/report_list.html b/trac/ticket/templates/report_list.html
    a b  
    6565            <span id="trac-sort-order" py:with="report_asc = asc if sort == 'report' else None; 
    6666                                                title_asc = asc if sort == 'title' else None"> 
    6767              Sort by: 
    68               <a href="${href.report(sort='report', asc=report_asc and '0' or '1')}" 
     68              <a href="${href.report(sort='report', asc='0' if report_asc else '1')}" 
    6969                 class="${('desc', 'asc')[report_asc] if report_asc is not None else None}"> 
    7070                Identifier</a> 
    71               <a href="${href.report(sort='title', asc=title_asc and '0' or '1')}" 
     71              <a href="${href.report(sort='title', asc='0' if title_asc else '1')}" 
    7272                 class="${('desc', 'asc')[title_asc] if title_asc is not None else None}"> 
    7373                Title</a> 
    7474            </span> 
  • trac/ticket/templates/report_view.html

    diff --git a/trac/ticket/templates/report_view.html b/trac/ticket/templates/report_view.html
    a b  
    8383      <py:def function="column_headers()"> 
    8484        <tr py:for="header_group in header_groups" class="trac-columns"> 
    8585          <th py:for="header in header_group" py:if="not header.hidden" py:with="fullrow = header is header_group[-1]" 
    86               colspan="${fullrow and '100' or None}" class="${header.asc is not None and ('desc', 'asc')[header.asc] or None}"> 
     86              colspan="${'100' if fullrow else None}" class="${('desc', 'asc')[header.asc] if header.asc is not None else None}"> 
    8787            <a py:strip="not sorting_enabled" 
    8888              href="${report_href(sort=header.col, asc=not header.asc)}"> 
    8989              $header.title 
     
    9595        <h2 py:if="value_for_group" class="report-result"> 
    9696          <a py:strip="not row_group or '__grouplink__' not in row_group[0]" href="${row_group[0]['__grouplink__']}">$value_for_group</a> 
    9797          <span class="numrows" py:with="cnt = len(row_group)"> 
    98             (${cnt and ngettext('%(num)s match', '%(num)s matches', cnt) or _('No matches found.')}) 
     98            (${ngettext('%(num)s match', '%(num)s matches', cnt) if cnt else _('No matches found.')}) 
    9999          </span> 
    100100        </h2> 
    101101      </py:def> 
    102       ${row_groups and group_heading(*row_groups[0]) or None} 
     102      ${group_heading(*row_groups[0]) if row_groups else None} 
    103103      <table py:if="row_groups" class="listing tickets"> 
    104104        <py:for each="groupindex, (value_for_group, row_group) in enumerate(row_groups)"> 
    105105          <thead py:if="not groupindex"> 
     
    118118            <py:for each="row in row_group"> 
    119119              <tr py:for="cell_group in row.cell_groups" 
    120120                py:with="fullrow = len(cell_group) == 1; 
    121                          td_attrs = fullrow and {'class': 'fullrow', 'colspan': 100} or {}" 
    122                 class="${'__color__' in row and 'color'+row.__color__+'-' or ''}${row.__idx__ % 2 and 'odd' or 'even'}" 
    123                 style="${'__bgcolor__' in row and 'background: '+row.__bgcolor__+';' or None 
    124                 }${'__fgcolor__' in row and 'color: '+row.__fgcolor__+';' or None 
    125                 }${'__style__' in row and row.__style__+';' or None 
    126                 }${fullrow and 'border: none; padding: 0;' or None}"> 
     121                         td_attrs = {'class': 'fullrow', 'colspan': 100} if fullrow else {}" 
     122                class="${'color' + row.__color__ + '-' if '__color__' in row else ''}${'odd' if row.__idx__ % 2 else 'even'}" 
     123                style="${'background: ' + row.__bgcolor__ + ';' if '__bgcolor__' in row else None 
     124                }${'color: ' + row.__fgcolor__ + ';' if '__fgcolor__' in row else None 
     125                }${row.__style__ + ';' if '__style__' in row else None 
     126                }${'border: none; padding: 0;' if fullrow else None}"> 
    127127 
    128128                <py:for each="cell in cell_group"> 
    129129                  <py:if test="not cell.header.hidden"> 
     
    155155 
    156156                        <!--! generic fields --> 
    157157                        <py:when test="col == 'time'"> 
    158                           <td class="date" py:attrs="td_attrs">${cell.value != '' and format_time(from_utimestamp(long(cell.value))) or '--'} 
     158                          <td class="date" py:attrs="td_attrs">${format_time(from_utimestamp(long(cell.value))) if cell.value != '' else '--'} 
    159159                            <hr py:if="fullrow"/> 
    160160                          </td> 
    161161                        </py:when> 
    162162 
    163163                        <py:when test="col in ('date', 'created', 'modified')"> 
    164                           <td class="date" py:attrs="td_attrs">${cell.value != '' and format_date(from_utimestamp(long(cell.value))) or '--'} 
     164                          <td class="date" py:attrs="td_attrs">${format_date(from_utimestamp(long(cell.value))) if cell.value != '' else '--'} 
    165165                            <hr py:if="fullrow"/> 
    166166                          </td> 
    167167                        </py:when> 
    168168 
    169169                        <py:when test="col == 'datetime'"> 
    170                           <td class="date" py:attrs="td_attrs">${cell.value != '' and format_datetime(from_utimestamp(long(cell.value))) or '--'} 
     170                          <td class="date" py:attrs="td_attrs">${format_datetime(from_utimestamp(long(cell.value))) if cell.value != '' else '--'} 
    171171                            <hr py:if="fullrow"/> 
    172172                          </td> 
    173173                        </py:when> 
  • trac/ticket/templates/ticket.html

    diff --git a/trac/ticket/templates/ticket.html b/trac/ticket/templates/ticket.html
    a b  
    127127                             show_editor = can_edit_comment and str(change.cnum) == cnum_edit; 
    128128                             show_history = str(change.cnum) == cnum_hist; 
    129129                             max_version = max(change.comment_history); 
    130                              comment_version = (max_version, int(cversion or 0))[show_history]"> 
    131               <div class="change" id="${'cnum' in change and 'trac-change-%d' % change.cnum or None}"> 
     130                             comment_version = int(cversion or 0) if show_history else max_version"> 
     131              <div class="change" id="${'trac-change-%d' % change.cnum if 'cnum' in change else None}"> 
    132132                <h3 class="change"> 
    133133                  <span class="threading" py:if="'cnum' in change" 
    134134                        py:with="change_replies = replies.get(str(change.cnum), [])"> 
     
    167167                </py:if> 
    168168                <xi:include href="ticket_change.html"/> 
    169169                <div py:if="not show_editor and len(change.comment_history) > 1" py:choose="" 
    170                      class="trac-lastedit ${comment_version != max_version and 'trac-shade' or None}"> 
     170                     class="trac-lastedit ${'trac-shade' if comment_version != max_version else None}"> 
    171171                  <i18n:msg params="version, date, author" py:when="comment_version != max_version"> 
    172172                      Version ${comment_version}, edited ${dateinfo(change.comment_history[comment_version].date)} ago 
    173173                      by ${authorinfo(change.comment_history[comment_version].author)} 
     
    197197      <!--! End of the section we don't show on initial new tickets --> 
    198198 
    199199      <form py:if="has_property_editor" method="post" id="propertyform" 
    200             action="${ticket.exists and href.ticket(ticket.id) + '#trac-add-comment' or href.newticket()}"> 
     200            action="${href.ticket(ticket.id) + '#trac-add-comment' if ticket.exists else href.newticket()}"> 
    201201        <!--! Add comment --> 
    202202        <div py:if="ticket.exists and can_append" class="field" 
    203203             py:with="show_comment_preview = (change_preview.fields or change_preview.comment) and cnum_edit is None"> 
     
    221221            may have failed. 
    222222          </div> 
    223223          <!--! Preview of ticket changes --> 
    224           <div id="ticketchange" class="ticketdraft" style="${not show_comment_preview and 'display: none' or None}"> 
    225             <h3 class="change" id="${'cnum' in change_preview and 'comment:%d' % change_preview.cnum or None}"> 
     224          <div id="ticketchange" class="ticketdraft" style="${'display: none' if not show_comment_preview else None}"> 
     225            <h3 class="change" id="${'comment:%d' % change_preview.cnum if 'cnum' in change_preview else None}"> 
    226226              <span class="threading" py:if="'replyto' in change_preview"> 
    227227                in reply to: ${commentref('&uarr;&nbsp;', change_preview.replyto)} 
    228228              </span> 
     
    285285                        field.edit_label or field.label or field.name}:</label> 
    286286                    </th> 
    287287                    <td class="col${idx + 1}" py:if="idx == 0 or not fullrow" 
    288                         colspan="${fullrow and 3 or None}"> 
     288                        colspan="${3 if fullrow else None}"> 
    289289                      <py:choose test="field.type" py:if="field"> 
    290290                        <select py:when="'select'" id="field-${field.name}" name="field_${field.name}"> 
    291291                          <option py:if="field.optional"></option> 
     
    302302                        </select> 
    303303                        <textarea py:when="'textarea'" id="field-${field.name}" name="field_${field.name}" 
    304304                                  cols="${field.width}" rows="${field.height}" 
    305                                   class="${field.format == 'wiki' and 'wikitext ' or None}trac-resizable"> 
     305                                  class="${'wikitext ' if field.format == 'wiki' else None}trac-resizable"> 
    306306${value}</textarea> 
    307307                        <span py:when="'checkbox'"> 
    308308                          <input type="checkbox" id="field-${field.name}" name="field_${field.name}" 
    309                                  checked="${value == '1' and 'checked' or None}" value="1" /> 
     309                                 checked="${value == '1' or None}" value="1" /> 
    310310                          <input type="hidden" name="field_checkbox_${field.name}" value="1" /> 
    311311                        </span> 
    312312                        <label py:when="'radio'" 
     
    404404            <input type="hidden" name="cnum" value="${cnum}" /> 
    405405          </py:if> 
    406406          <input type="submit" name="preview" value="${_('Preview')}" accesskey="r" />&nbsp; 
    407           <input type="submit" name="submit" value="${ticket.exists and _('Submit changes') or _('Create ticket')}" /> 
     407          <input type="submit" name="submit" value="${_('Submit changes') if ticket.exists else _('Create ticket')}" /> 
    408408        </div> 
    409409 
    410410      </form> 
  • trac/ticket/templates/ticket_box.html

    diff --git a/trac/ticket/templates/ticket_box.html b/trac/ticket/templates/ticket_box.html
    a b Arguments: 
    1414     xmlns:py="http://genshi.edgewall.org/" 
    1515     xmlns:xi="http://www.w3.org/2001/XInclude" 
    1616     xmlns:i18n="http://genshi.edgewall.org/i18n" 
    17      id="ticket" class="${preview_mode and 'ticketdraft' or None}"> 
     17     id="ticket" class="${'ticketdraft' if preview_mode else None}"> 
    1818  <div class="date"> 
    1919    <p i18n:msg="created" py:if="ticket.exists">Opened ${dateinfo(ticket.time)} ago</p> 
    2020    <p i18n:msg="modified" py:if="ticket.changetime != ticket.time">Last modified ${dateinfo(ticket.changetime)} ago</p> 
    Arguments: 
    2828    <tr> 
    2929      <th id="h_reporter">Reported by:</th> 
    3030      <td headers="h_reporter" class="searchable"> 
    31         ${defined('reporter_link') and reporter_link or authorinfo(ticket.reporter)} 
     31        ${reporter_link if defined('reporter_link') else authorinfo(ticket.reporter)} 
    3232      </td> 
    3333      <th id="h_owner">Owned by:</th> 
    3434      <td headers="h_owner"> 
    35         ${ticket.owner and (defined('owner_link') and owner_link or authorinfo(ticket.owner)) or ''} 
     35        ${(owner_link if defined('owner_link') else authorinfo(ticket.owner)) if ticket.owner else ''} 
    3636      </td> 
    3737    </tr> 
    3838    <tr py:for="row in group(fields, 2, lambda f: f.type != 'textarea')" 
    3939      py:with="fullrow = len(row) == 1"> 
    4040      <py:for each="idx, field in enumerate(row)"> 
    4141        <th py:if="idx == 0 or not fullrow" 
    42             id="${field and 'h_' + field.name or None}"> 
     42            id="${'h_' + field.name if field else None}"> 
    4343          <py:if test="field"><i18n:msg params="field">${field.label or field.name}:</i18n:msg></py:if> 
    4444        </th> 
    4545        <td py:if="idx == 0 or not fullrow" 
    46             headers="${field and 'h_' + field.name or None}" 
    47             class="${field and field.name in ('cc', 'keywords') and 'searchable' or None}" 
    48             colspan="${fullrow and 3 or None}"> 
     46            headers="${'h_' + field.name if field else None}" 
     47            class="${'searchable' if field and field.name in ('cc', 'keywords') else None}" 
     48            colspan="${3 if fullrow else None}"> 
    4949          <py:if test="field"> 
    5050            <py:choose test=""> 
    5151              <py:when test="'rendered' in field">${field.rendered}</py:when> 
  • trac/ticket/templates/ticket_change.html

    diff --git a/trac/ticket/templates/ticket_change.html b/trac/ticket/templates/ticket_change.html
    a b Arguments: 
    3838  <form py:if="show_editor" id="trac-comment-editor" method="post" action="#comment:${change.cnum}"> 
    3939    <div> 
    4040      <textarea name="edited_comment" class="wikitext trac-resizable" rows="10" cols="78"> 
    41 ${(edited_comment, change.comment)[edited_comment is None]}</textarea> 
     41${edited_comment if edited_comment is not None else change.comment}</textarea> 
    4242      <input type="hidden" name="cnum_edit" value="${change.cnum}"/> 
    4343    </div> 
    4444    <div class="buttons"> 
    Arguments: 
    5151    </div> 
    5252  </form> 
    5353  <py:choose> 
    54     <div py:when="str(change.cnum) == cnum_edit" py:with="text = (edited_comment, change.comment)[edited_comment is None]" 
    55          class="comment searchable ticketdraft" style="${not text and 'display: none' or None}" xml:space="preserve"> 
     54    <div py:when="str(change.cnum) == cnum_edit" 
     55         py:with="text = edited_comment if edited_comment is not None else change.comment" 
     56         class="comment searchable ticketdraft" style="${'display: none' if not text else None}" xml:space="preserve"> 
    5657      ${wiki_to_html(context, text, escape_newlines=preserve_newlines)} 
    5758    </div> 
    5859    <div py:otherwise="" py:choose="" class="comment searchable" xml:space="preserve"> 
  • trac/ticket/templates/ticket_notify_email.txt

    diff --git a/trac/ticket/templates/ticket_notify_email.txt b/trac/ticket/templates/ticket_notify_email.txt
    a b  
    1919{%     end %}\ 
    2020{%     if change.comment %}\ 
    2121 
    22 ${changes_body and _('Comment:') or _('Comment (by %(author)s):', author=change.author)} 
     22${_('Comment:') if changes_body else _('Comment (by %(author)s):', author=change.author)} 
    2323 
    2424$change.comment 
    2525{%     end %}\ 
  • trac/ticket/tests/notification.py

    diff --git a/trac/ticket/tests/notification.py b/trac/ticket/tests/notification.py
    a b class NotificationTestCase(unittest.Test 
    176176        def run_bcc_feature(public): 
    177177            # CC list should be private 
    178178            self.env.config.set('notification', 'use_public_cc', 
    179                                 public and 'true' or 'false') 
     179                                'true' if public else 'false') 
    180180            self.env.config.set('notification', 'smtp_always_bcc',  
    181181                                'joe.foobar@example.net') 
    182182            ticket = Ticket(self.env) 
  • trac/ticket/web_ui.py

    diff --git a/trac/ticket/web_ui.py b/trac/ticket/web_ui.py
    a b class TicketModule(Component): 
    576576        format = req.args.get('format') 
    577577        if format: 
    578578            # FIXME: mime.send_converted(context, ticket, 'ticket_x') (#3332) 
    579             filename = ('t%d' % ticket.id, None)[format == 'rss'] 
     579            filename = 't%d' % ticket.id if format != 'rss' else None 
    580580            mime.send_converted(req, 'trac.ticket.Ticket', ticket, 
    581581                                format, filename=filename) 
    582582 
    class TicketModule(Component): 
    848848 
    849849        for field in text_fields: 
    850850            old_text = old_ticket.get(field) 
    851             old_text = old_text and old_text.splitlines() or [] 
     851            old_text = old_text.splitlines() if old_text else [] 
    852852            new_text = new_ticket.get(field) 
    853             new_text = new_text and new_text.splitlines() or [] 
     853            new_text = new_text.splitlines() if new_text else [] 
    854854            diffs = diff_blocks(old_text, new_text, context=diff_context, 
    855855                                ignore_blank_lines='-B' in diff_options, 
    856856                                ignore_case='-i' in diff_options, 
    class TicketModule(Component): 
    894894 
    895895    def _make_comment_url(self, req, ticket, cnum, version=None): 
    896896        return req.href.ticket(ticket.id, 
    897                                cnum_hist=version is not None and cnum or None, 
     897                               cnum_hist=cnum if version is not None else None, 
    898898                               cversion=version) + '#comment:%d' % cnum 
    899899 
    900900    def _get_comment_history(self, req, ticket, cnum): 
    class TicketModule(Component): 
    902902        for version, date, author, comment in ticket.get_comment_history(cnum): 
    903903            history.append({ 
    904904                'version': version, 'date': date, 'author': author, 
    905                 'comment': version == 0 and _("''Initial version''") or '', 
     905                'comment': _("''Initial version''") if version == 0 else '', 
    906906                'value': comment, 
    907907                'url': self._make_comment_url(req, ticket, cnum, version) 
    908908            }) 
    class TicketModule(Component): 
    962962        def get_text(version): 
    963963            try: 
    964964                text = history[version]['value'] 
    965                 return text and text.splitlines() or [] 
     965                return text.splitlines() if text else [] 
    966966            except KeyError: 
    967967                raise ResourceNotFound(_("No version %(version)d for comment " 
    968968                                         "%(cnum)d on ticket #%(ticket)s", 
    class TicketModule(Component): 
    12431243        if ticket.save_changes(get_reporter_id(req, 'author'), 
    12441244                                     req.args.get('comment'), when=now, 
    12451245                                     cnum=internal_cnum): 
    1246             fragment = cnum and '#comment:' + cnum or '' 
     1246            fragment = '#comment:' + cnum if cnum else '' 
    12471247            try: 
    12481248                tn = TicketNotifyEmail(self.env) 
    12491249                tn.notify(ticket, newticket=False, modtime=now) 
    class TicketModule(Component): 
    14201420                value = ticket.values.get(name) 
    14211421                if value in ('1', '0'): 
    14221422                    field['rendered'] = self._query_link(req, name, value, 
    1423                                 value == '1' and _("yes") or _("no")) 
     1423                                _("yes") if value == '1' else _("no")) 
    14241424            elif type_ == 'text': 
    14251425                if field.get('format') == 'wiki': 
    14261426                    field['rendered'] = format_to_oneliner(self.env, context, 
    class TicketModule(Component): 
    16061606                type_ = f['type'] 
    16071607                break 
    16081608        if type_ == 'checkbox': 
    1609             rendered = new == '1' and _("set") or _("unset") 
     1609            rendered = _("set") if new == '1' else _("unset") 
    16101610        elif type_ == 'textarea': 
    16111611            if not resource_new: 
    16121612                rendered = _("modified") 
    class TicketModule(Component): 
    16671667        autonum = 0 # used for "root" numbers 
    16681668        last_uid = current = None 
    16691669        for date, author, field, old, new, permanent in changelog: 
    1670             uid = permanent and (date,) or (date, author) 
     1670            uid = (date,) if permanent else (date, author) 
    16711671            if uid != last_uid: 
    16721672                if current: 
    16731673                    last_comment = comment_history[max(comment_history)] 
  • trac/timeline/templates/timeline.html

    diff --git a/trac/timeline/templates/timeline.html b/trac/timeline/templates/timeline.html
    a b  
    3333      </form> 
    3434 
    3535      <py:for each="day, events in groupby(events, key=lambda e: format_date(e.date))"> 
    36         <h2>${day}: ${day == today and _("Today") or day == yesterday and _("Yesterday") or None}</h2> 
     36        <h2>${day}: ${_("Today") if day == today else _("Yesterday") if day == yesterday else None}</h2> 
    3737        <dl py:for="unread, events in groupby(events, key=lambda e: lastvisit and lastvisit &lt; e.dateuid)" 
    38             class="${unread and 'unread' or None}"> 
     38            class="${'unread' if unread else None}"> 
    3939          <py:for each="event in events" 
    4040            py:with="highlight = precision and precisedate and timedelta(0) &lt;= (event.date - precisedate) &lt; precision"> 
    4141            <dt class="${classes(event.kind, highlight=highlight, unread=unread)}"> 
  • trac/timeline/web_ui.py

    diff --git a/trac/timeline/web_ui.py b/trac/timeline/web_ui.py
    a b class TimelineModule(Component): 
    9090        req.perm.assert_permission('TIMELINE_VIEW') 
    9191 
    9292        format = req.args.get('format') 
    93         maxrows = int(req.args.get('max', format == 'rss' and 50 or 0)) 
     93        maxrows = int(req.args.get('max', 50 if format == 'rss' else 0)) 
    9494        lastvisit = int(req.session.get('timeline.lastvisit', '0')) 
    9595 
    9696        # indication of new events is unchanged when form is updated by user 
    class TimelineModule(Component): 
    123123                                    microsecond=999999) 
    124124 
    125125        daysback = as_int(req.args.get('daysback'), 
    126                           format == 'rss' and 90 or None) 
     126                          90 if format == 'rss' else None) 
    127127        if daysback is None: 
    128128            daysback = as_int(req.session.get('timeline.daysback'), None) 
    129129        if daysback is None: 
    class TimelineModule(Component): 
    188188                for event in provider.get_timeline_events(req, start, stop, 
    189189                                                          filters) or []: 
    190190                    # Check for 0.10 events 
    191                     author = (event[len(event) < 6 and 2 or 4] or '').lower() 
     191                    author = (event[2 if len(event) < 6 else 4] or '').lower() 
    192192                    if (not include or author in include) \ 
    193193                       and not author in exclude: 
    194194                        events.append(self._event_data(provider, event)) 
  • trac/util/__init__.py

    diff --git a/trac/util/__init__.py b/trac/util/__init__.py
    a b def get_doc(obj): 
    496496        return (None, None) 
    497497    doc = to_unicode(doc).split('\n\n', 1) 
    498498    summary = doc[0].replace('\n', ' ') 
    499     description = len(doc) > 1 and doc[1] or None 
     499    description = doc[1] if len(doc) > 1 else None 
    500500    return (summary, description) 
    501501 
    502502# -- setuptools utils 
  • trac/util/datefmt.py

    diff --git a/trac/util/datefmt.py b/trac/util/datefmt.py
    a b def _parse_date_iso8601(text, tzinfo): 
    308308                if tz == 0: 
    309309                    tzinfo = utc 
    310310                else: 
    311                     tzinfo = FixedOffset(tzsign == '-' and -tz or tz, 
     311                    tzinfo = FixedOffset(-tz if tzsign == '-' else tz, 
    312312                                         '%s%s:%s' % 
    313313                                         (tzsign, tzhours, tzminutes)) 
    314314            tm = time.strptime('%s ' * 6 % (years, months, days, 
  • trac/util/text.py

    diff --git a/trac/util/text.py b/trac/util/text.py
    a b def text_width(text, ambiwidth=1): 
    203203 
    204204    cf. http://www.unicode.org/reports/tr11/. 
    205205    """ 
    206     twice = ('FW', 'FWA')[ambiwidth == 2] 
    207     return sum([(1, 2)[east_asian_width(chr) in twice] 
     206    twice = 'FWA' if ambiwidth == 2 else 'FW' 
     207    return sum([2 if east_asian_width(chr) in twice else 1 
    208208                for chr in to_unicode(text)]) 
    209209 
    210210def print_table(data, headers=None, sep='  ', out=None): 
    def obfuscate_email_address(address): 
    419419        at = address.find('@') 
    420420        if at != -1: 
    421421            return address[:at] + u'@\u2026' + \ 
    422                    (address[-1] == '>' and '>' or '') 
     422                   ('>' if address[-1] == '>' else '') 
    423423    return address 
    424424 
    425425def breakable_path(path): 
  • trac/util/translation.py

    diff --git a/trac/util/translation.py b/trac/util/translation.py
    a b  
    1111# individuals. For the exact contribution history, see the revision 
    1212# history and logs, available at http://trac.edgewall.org/log/. 
    1313 
     14"""Utilities for text translation with gettext.""" 
     15 
    1416from __future__ import with_statement 
    1517 
    16 """Utilities for text translation with gettext.""" 
    17  
    1818import pkg_resources 
    1919import re 
    2020 
    def dgettext_noop(domain, string, **kwar 
    4444N_ = _noop = lambda string: string 
    4545 
    4646def ngettext_noop(singular, plural, num, **kwargs): 
    47     string = (plural, singular)[num == 1] 
     47    string = singular if num == 1 else plural 
    4848    kwargs.setdefault('num', num) 
    4949    return safefmt(string, kwargs) 
    5050 
    def _tag_kwargs(trans, kwargs): 
    5959    return tag(*trans_elts) 
    6060 
    6161def tgettext_noop(string, **kwargs): 
    62     return kwargs and _tag_kwargs(string, kwargs) or string 
     62    return _tag_kwargs(string, kwargs) if kwargs else string 
    6363 
    6464def dtgettext_noop(domain, string, **kwargs): 
    6565    return tgettext_noop(string, **kwargs) 
    6666 
    6767def tngettext_noop(singular, plural, num, **kwargs): 
    68     string = (plural, singular)[num == 1] 
     68    string = singular if num == 1 else plural 
    6969    kwargs.setdefault('num', num) 
    7070    return _tag_kwargs(string, kwargs) 
    7171 
    try: 
    221221        def tgettext(self, string, **kwargs): 
    222222            def _tgettext(): 
    223223                trans = self.active.ugettext(string) 
    224                 return kwargs and _tag_kwargs(trans, kwargs) or trans 
     224                return _tag_kwargs(trans, kwargs) if kwargs else trans 
    225225            if not self.isactive: 
    226226                return LazyProxy(_tgettext) 
    227227            return _tgettext() 
    try: 
    229229        def dtgettext(self, domain, string, **kwargs): 
    230230            def _dtgettext(): 
    231231                trans = self.active.dugettext(domain, string) 
    232                 return kwargs and _tag_kwargs(trans, kwargs) or trans 
     232                return _tag_kwargs(trans, kwargs) if kwargs else trans 
    233233            if not self.isactive: 
    234234                return LazyProxy(_dtgettext) 
    235235            return _dtgettext() 
    try: 
    250250                trans = self.active.dungettext(domain, singular, plural, num) 
    251251                if '%(num)' in trans: 
    252252                    kwargs.update(num=num) 
    253                 return kwargs and _tag_kwargs(trans, kwargs) or trans 
     253                return _tag_kwargs(trans, kwargs) if kwargs else trans 
    254254            if not self.isactive: 
    255255                return LazyProxy(_dtngettext) 
    256256            return _dtngettext() 
  • trac/versioncontrol/admin.py

    diff --git a/trac/versioncontrol/admin.py b/trac/versioncontrol/admin.py
    a b class RepositoryAdminPanel(Component): 
    189189         
    190190        if path_info: 
    191191            # Detail view 
    192             reponame = not is_default(path_info) and path_info or '' 
     192            reponame = path_info if not is_default(path_info) else '' 
    193193            info = all_repos.get(reponame) 
    194194            if info is None: 
    195195                raise TracError(_("Repository '%(repo)s' not found", 
  • trac/versioncontrol/api.py

    diff --git a/trac/versioncontrol/api.py b/trac/versioncontrol/api.py
    a b class RepositoryManager(Component): 
    386386                kind = _("path") 
    387387                if resource.version: 
    388388                    version = '@%s' % resource.version 
    389             in_repo = reponame and _(" in %(repo)s", repo=reponame) or '' 
     389            in_repo = _(" in %(repo)s", repo=reponame) if reponame else '' 
    390390            # TRANSLATOR: file /path/to/file.py at version 13 in reponame 
    391391            return _('%(kind)s %(id)s%(at_version)s%(in_repo)s', 
    392392                     kind=kind, id=id, at_version=version, in_repo=in_repo) 
    class RepositoryManager(Component): 
    551551                 been truncated, if needed. 
    552552        """ 
    553553        matches = [] 
    554         path = path and path.strip('/') + '/' or '/' 
     554        path = path.strip('/') + '/' if path else '/' 
    555555        for reponame in self.get_all_repositories().keys(): 
    556556            stripped_reponame = reponame.strip('/') + '/' 
    557557            if path.startswith(stripped_reponame): 
    class Node(object): 
    10611061 
    10621062    def is_viewable(self, perm): 
    10631063        """Return True if view permission is granted on the node.""" 
    1064         return (self.isdir and 'BROWSER_VIEW' or 'FILE_VIEW') \ 
     1064        return ('BROWSER_VIEW' if self.isdir else 'FILE_VIEW') \ 
    10651065               in perm(self.resource) 
    10661066 
    10671067    can_view = is_viewable  # 0.12 compatibility 
  • trac/versioncontrol/cache.py

    diff --git a/trac/versioncontrol/cache.py b/trac/versioncontrol/cache.py
    a b class CachedRepository(Repository): 
    346346                for i in range(1, len(components) + 1): 
    347347                    args.append('/'.join(components[:i])) 
    348348 
    349             sql += " ORDER BY rev" + (direction == '<' and " DESC" or "") \ 
     349            sql += " ORDER BY rev" + (" DESC" if direction == '<' else "") \ 
    350350                   + " LIMIT 1" 
    351351             
    352352            for rev, in db(sql, args): 
  • trac/versioncontrol/diff.py

    diff --git a/trac/versioncontrol/diff.py b/trac/versioncontrol/diff.py
    a b def get_diff_options(req): 
    331331     
    332332    arg = int(req.args.get('contextall', 0)) 
    333333    options_data['contextall'] = arg 
    334     options = ['-U%d' % (arg and -1 or context)] 
     334    options = ['-U%d' % (-1 if arg else context)] 
    335335 
    336336    arg = get_bool_option('ignoreblanklines') 
    337337    if arg: 
  • trac/versioncontrol/svn_authz.py

    diff --git a/trac/versioncontrol/svn_authz.py b/trac/versioncontrol/svn_authz.py
    a b def parse(authz, modules): 
    8383            aliases[name] = value.strip() 
    8484        else: 
    8585            parts = section.split(':', 1) 
    86             module, path = len(parts) > 1 and parts[0] or '', parts[-1] 
     86            module, path = parts[0] if len(parts) > 1 else '', parts[-1] 
    8787            if module in modules: 
    8888                sections.setdefault((module, path), []).append((name, value)) 
    8989 
    class AuthzSourcePolicy(Component): 
    149149    # IPermissionPolicy methods 
    150150 
    151151    def check_permission(self, action, username, resource, perm): 
    152         realm = resource and resource.realm or None 
     152        realm = resource.realm if resource else None 
    153153        if (realm, action) in self._handled_perms: 
    154154            authz, users = self._get_authz_info() 
    155155            if authz is None: 
    class AuthzSourcePolicy(Component): 
    160160            else: 
    161161                usernames = (username, '$authenticated', '*') 
    162162            if resource is None: 
    163                 return users & set(usernames) and True or None 
     163                return True if users & set(usernames) else None 
    164164 
    165165            rm = RepositoryManager(self.env) 
    166166            try: 
  • trac/versioncontrol/svn_fs.py

    diff --git a/trac/versioncontrol/svn_fs.py b/trac/versioncontrol/svn_fs.py
    a b def _is_path_within_scope(scope, fullpat 
    117117    """Check whether the given `fullpath` is within the given `scope`""" 
    118118    if scope == '/': 
    119119        return fullpath is not None 
    120     fullpath = fullpath and fullpath.lstrip('/') or '' 
     120    fullpath = fullpath.lstrip('/') if fullpath else '' 
    121121    scope = scope.strip('/') 
    122122    return (fullpath + '/').startswith(scope + '/') 
    123123 
    class SubversionRepository(Repository): 
    360360            self.scope = '/' 
    361361        assert self.scope[0] == '/' 
    362362        # we keep root_path_utf8 for  RA  
    363         ra_prefix = os.name == 'nt' and 'file:///' or 'file://' 
     363        ra_prefix = 'file:///' if os.name == 'nt' else 'file://' 
    364364        self.ra_url_utf8 = ra_prefix + root_path_utf8 
    365365        self.clear() 
    366366 
  • trac/versioncontrol/svn_prop.py

    diff --git a/trac/versioncontrol/svn_prop.py b/trac/versioncontrol/svn_prop.py
    a b class SubversionPropertyRenderer(Compone 
    7979    def match_property(self, name, mode): 
    8080        if name in ('svn:externals', 'svn:needs-lock'): 
    8181            return 4 
    82         return name in ('svn:mergeinfo', 'svnmerge-blocked', 
    83                         'svnmerge-integrated') and 2 or 0 
     82        return 2 if name in ('svn:mergeinfo', 'svnmerge-blocked', 
     83                             'svnmerge-integrated') else 0 
    8484     
    8585    def render_property(self, name, mode, context, props): 
    8686        if name == 'svn:externals': 
    class SubversionPropertyRenderer(Compone 
    124124                base_url, pref = posixpath.split(base_url) 
    125125                prefix.append(pref) 
    126126            href = self._externals_map.get(base_url) 
    127             revstr = rev and ' at revision '+rev or '' 
     127            revstr = ' at revision ' + rev if rev else '' 
    128128            if not href and (url.startswith('http://') or  
    129129                             url.startswith('https://')): 
    130130                href = url.replace('%', '%%') 
    class SubversionMergePropertyRenderer(Co 
    175175    # IPropertyRenderer methods 
    176176 
    177177    def match_property(self, name, mode): 
    178         return name in ('svn:mergeinfo', 'svnmerge-blocked', 
    179                         'svnmerge-integrated') and 4 or 0 
     178        return 4 if name in ('svn:mergeinfo', 'svnmerge-blocked', 
     179                             'svnmerge-integrated') else 0 
    180180     
    181181    def render_property(self, name, mode, context, props): 
    182182        """Parse svn:mergeinfo and svnmerge-* properties, converting branch 
    class SubversionMergePropertyRenderer(Co 
    184184        and eligible revisions. 
    185185        """ 
    186186        has_eligible = name in ('svnmerge-integrated', 'svn:mergeinfo') 
    187         revs_label = (_('merged'), _('blocked'))[name.endswith('blocked')] 
    188         revs_cols = has_eligible and 2 or None 
     187        revs_label = _('blocked') if name.endswith('blocked') else _('merged') 
     188        revs_cols = 2 if has_eligible else None 
    189189        reponame = context.resource.parent.id 
    190190        target_path = context.resource.id 
    191191        repos = RepositoryManager(self.env).get_repository(reponame) 
    class SubversionMergePropertyRenderer(Co 
    249249        if not rows: 
    250250            return None 
    251251        rows.sort() 
    252         has_deleted = rows and rows[-1][0] or None 
     252        has_deleted = rows[-1][0] if rows else None 
    253253        return tag(has_deleted and tag.a(_('(toggle deleted branches)'), 
    254254                                         class_='trac-toggledeleted', 
    255255                                         href='#'), 
    256256                   tag.table(tag.tbody( 
    257                        [tag.tr(row, class_=deleted and 'trac-deleted' or None) 
     257                       [tag.tr(row, class_='trac-deleted' if deleted else None) 
    258258                        for deleted, spath, row in rows]), class_='props')) 
    259259 
    260260 
    class SubversionMergePropertyDiffRendere 
    318318    # IPropertyDiffRenderer methods 
    319319 
    320320    def match_property_diff(self, name): 
    321         return name in ('svn:mergeinfo', 'svnmerge-blocked', 
    322                         'svnmerge-integrated') and 4 or 0 
     321        return 4 if name in ('svn:mergeinfo', 'svnmerge-blocked', 
     322                             'svnmerge-integrated') else 0 
    323323 
    324324    def render_property_diff(self, name, old_context, old_props, 
    325325                             new_context, new_props, options): 
  • trac/versioncontrol/templates/admin_repositories.html

    diff --git a/trac/versioncontrol/templates/admin_repositories.html b/trac/versioncontrol/templates/admin_repositories.html
    a b  
    131131                <td class="name"> 
    132132                  <a href="${panel_href(info.name or '(default)')}">${info.name or _('(default)')}</a> 
    133133                </td> 
    134                 <td>${not info.alias and (info.type or _('(default)')) or None}</td> 
     134                <td>${(info.type or _('(default)')) if not info.alias else None}</td> 
    135135                <td py:choose=""> 
    136136                  <py:when test="info.dir">$info.prettydir</py:when> 
    137137                  <em py:otherwise="" i18n:msg="repo">Alias of ${info.alias or _('(default)')}</em> 
  • trac/versioncontrol/templates/browser.html

    diff --git a/trac/versioncontrol/templates/browser.html b/trac/versioncontrol/templates/browser.html
    a b  
    7373        <div id="jumprev"> 
    7474          <form action="" method="get"> 
    7575            <div> 
    76               <label for="rev" title="${stickyrev and _('Hint: clear the field to view latest revision') or None}"> 
     76              <label for="rev" title="${_('Hint: clear the field to view latest revision') if stickyrev else None}"> 
    7777                View revision:</label> 
    7878              <input type="text" id="rev" name="rev" value="$stickyrev" size="6" /> 
    7979            </div> 
  • trac/versioncontrol/templates/changeset.html

    diff --git a/trac/versioncontrol/templates/changeset.html b/trac/versioncontrol/templates/changeset.html
    a b  
    7878 
    7979      <form py:if="not xhr and (has_diffs or diff.options.ignoreblanklines or diff.options.ignorecase or 
    8080                                diff.options.ignorewhitespace)" 
    81         id="prefs" action=""> 
     81            id="prefs" action=""> 
    8282        <div> 
    8383          <py:if test="not changeset"> 
    8484            <input type="hidden" name="old_path" value="${'/' + pathjoin(reponame, old_path)}" /> 
     
    9191      </form> 
    9292 
    9393      <py:def function="node_change(idx,item,cl,kind)"> 
    94         <py:with vars="ndiffs = item.diffs is not None and len(item.diffs) or 0; 
     94        <py:with vars="ndiffs = len(item.diffs) if item.diffs is not None else 0; 
    9595                       nprops = len(item.props); 
    9696                       is_removal = cl == 'rem'; 
    97                        path = is_removal and item.old.get('path') or item.new.get('path'); 
     97                       path = item.old.get('path') if is_removal else item.new.get('path'); 
    9898                       path = path and path[len(location):].strip('/')"> 
    9999          <div class="$cl"> </div> 
    100100          <py:choose> 
    101           <a py:when="is_removal" href="$item.old.href" 
    102              title="${_('Show what was removed (content at revision %(old_rev)s)', old_rev=display_rev(item.old.rev))}"> 
     101            <a py:when="is_removal" href="$item.old.href" 
     102               title="${_('Show what was removed (content at revision %(old_rev)s)', old_rev=display_rev(item.old.rev))}"> 
    103103              $path 
    104104            </a> 
    105105            <a py:otherwise="" title="Show entry in browser" href="$item.new.href"> 
     
    120120            </py:when> 
    121121            <py:when test="ndiffs + nprops &gt; 0"> 
    122122              (<a title="Show differences" href="#file$idx">${ 
    123                  ndiffs and ngettext('%(num)d diff', '%(num)d diffs', ndiffs) or None}${ 
    124                  (ndiffs and nprops) and ', ' or '' 
    125                 }${nprops and ngettext('%(num)d prop', '%(num)d props', nprops) or None}</a>) 
     123                 ngettext('%(num)d diff', '%(num)d diffs', ndiffs) if ndiffs else None}${ 
     124                 ', ' if ndiffs and nprops else None 
     125                }${ngettext('%(num)d prop', '%(num)d props', nprops) if nprops else None}</a>) 
    126126            </py:when> 
    127127          </py:choose> 
    128128          <py:if test="cl == 'mod' and item.diffs is None"> 
     
    167167          <dd class="searchable"><a href="${href.browser(reponame, location, rev=new_rev)}">$location</a></dd> 
    168168        </py:if> 
    169169        <dt class="property files"> 
    170           ${files and ngettext('File:', 'Files:', num=len(files)) or _('(No files)')} 
     170          ${ngettext('File:', 'Files:', num=len(files)) if files else _('(No files)')} 
    171171        </dt> 
    172172        <dd class="files"> 
    173173          <div class="legend" id="file-legend" py:if="filestats"> 
  • trac/versioncontrol/templates/dir_entries.html

    diff --git a/trac/versioncontrol/templates/dir_entries.html b/trac/versioncontrol/templates/dir_entries.html
    a b  
    77                   chgset_context = change and context.child('changeset', change.rev, parent=repos.resource); 
    88                   chgset_view = change and change.is_viewable(perm); 
    99                   isdir = entry.kind == 'dir'"> 
    10     <tr class="${idx % 2 and 'even' or 'odd'}"> 
     10    <tr class="${'odd' if idx % 2 else 'even'}"> 
    1111      <td class="name"> 
    1212        <a class="$entry.kind" title="${_('View Directory') if isdir else _('View File')}" 
    1313           href="${href.browser(reponame, entry.path, rev=stickyrev,  
    14                                 order=(order != 'name' and order or None), desc=desc)}">$entry.name</a> 
     14                                order=order if order != 'name' else None, desc=desc)}">$entry.name</a> 
    1515      </td> 
    1616      <td class="size"> 
    1717        <span title="${_('%(size)s bytes', size=entry.content_length)}">${pretty_size(entry.content_length)}</span> 
     
    2424      </td> 
    2525      <td class="age" style="${chgset_view and dir.timerange and 'border-color: rgb(%s,%s,%s)' % 
    2626                               dir.colorize_age(dir.timerange.relative(change.date)) or None}"> 
    27         ${chgset_view and dateinfo(change.date) or '&ndash;'} 
     27        ${dateinfo(change.date) if chgset_view else '&ndash;'} 
    2828      </td> 
    29       <td class="author">${chgset_view and authorinfo_short(change.author) or '&ndash;'}</td> 
     29      <td class="author">${authorinfo_short(change.author) if chgset_view else '&ndash;'}</td> 
    3030      <td class="change" py:choose=""> 
    3131        <py:when test="chgset_view" py:choose=""> 
    3232          <py:when test="wiki_format_messages">${wiki_to_oneliner(chgset_context, change.message, shorten=True)}</py:when> 
  • trac/versioncontrol/templates/repository_index.html

    diff --git a/trac/versioncontrol/templates/repository_index.html b/trac/versioncontrol/templates/repository_index.html
    a b  
    88      <py:for each="idx, (reponame, repoinfo, repos, change, err, raw_href) in enumerate(repo.repositories)" 
    99              py:with="chgset_context = change and context.child('changeset', change.rev, parent=repos.resource); 
    1010                       chgset_view = change and change.is_viewable(perm)"> 
    11         <tr class="${idx % 2 and 'even' or 'odd'}"> 
     11        <tr class="${'odd' if idx % 2 else 'even'}"> 
    1212          <td class="name"> 
    1313            <em py:strip="not err"> 
    1414              <b py:strip="repoinfo.alias != ''"> 
    1515                <a class="dir" title="View Root Directory" 
    1616                   href="${href.browser(repos.reponame if repos else reponame, 
    17                                         order=(order != 'name' and order or None), desc=desc)}">$reponame</a> 
     17                                        order=order if order != 'name' else None, desc=desc)}">$reponame</a> 
    1818              </b> 
    1919            </em> 
    2020          </td> 
     
    2929          </td> 
    3030          <td class="age" style="${chgset_view and change and repo.timerange and 'border-color: rgb(%s,%s,%s)' % 
    3131                                   repo.colorize_age(repo.timerange.relative(change.date)) or None}"> 
    32             ${chgset_view and dateinfo(change.date) or '&ndash;'} 
     32            ${dateinfo(change.date) if chgset_view else '&ndash;'} 
    3333          </td> 
    34           <td class="author">${chgset_view and authorinfo_short(change.author) or '&ndash;'}</td> 
     34          <td class="author">${authorinfo_short(change.author) if chgset_view else '&ndash;'}</td> 
    3535          <td class="change" py:choose=""> 
    3636            <py:when test="err"><em py:content="err"></em></py:when> 
    3737            <py:when test="chgset_view" py:choose=""> 
     
    4141            <py:otherwise>&ndash;</py:otherwise> 
    4242          </td> 
    4343        </tr> 
    44         <tr class="${idx % 2 and 'even' or 'odd'}" py:if="repoinfo.description"> 
     44        <tr class="${'odd' if idx % 2 else 'even'}" py:if="repoinfo.description"> 
    4545          <td class="description" colspan="6">${wiki_to_html(context.child('source', '/', parent=repos.resource), repoinfo.description)}</td> 
    4646        </tr> 
    4747      </py:for> 
  • trac/versioncontrol/templates/revisionlog.html

    diff --git a/trac/versioncontrol/templates/revisionlog.html b/trac/versioncontrol/templates/revisionlog.html
    a b  
    7777            </label> 
    7878          </i18n:msg><br /> 
    7979          <label> 
    80             <input type="checkbox" id="verbose" name="verbose" checked="${verbose and 'checked' or None}" /> 
     80            <input type="checkbox" id="verbose" name="verbose" checked="${verbose or None}" /> 
    8181            Show full log messages 
    8282          </label> 
    8383        </div> 
     
    106106          <input type="submit" value="${_('View changes')}" 
    107107            title="Diff from Old Revision to New Revision (as selected in the Diff column)" /> 
    108108        </div> 
    109         <table class="listing chglist${graph and ' trac-graph' or None}"> 
     109        <table class="listing chglist${' trac-graph' if graph else None}"> 
    110110          <thead> 
    111111            <tr> 
    112112              <th py:if="graph" class="trac-graph">Graph</th> 
     
    132132              <py:with vars="change = changes[item.rev]; 
    133133                             is_separator = item.change is None; 
    134134                             chgset_context = context.child('changeset', change.rev, parent=repos.resource); 
    135                              odd_even = idx % 2 and 'odd' or 'even'"> 
     135                             odd_even = 'odd' if idx % 2 else 'even'"> 
    136136                <!--! highlight copy or rename operations --> 
    137137                <tr py:if="not is_separator and item.get('copyfrom_path')" class="$odd_even"> 
    138138                  <td /> 
  • trac/versioncontrol/templates/revisionlog.txt

    diff --git a/trac/versioncontrol/templates/revisionlog.txt b/trac/versioncontrol/templates/revisionlog.txt
    a b  
    11# 
    2 # ${_('ChangeLog for %(path)s%(in_repo)s', path=path, in_repo=reponame and _(" in %(repo)s", repo=reponame) or '')} 
     2# ${_("ChangeLog for %(path)s in %(repo)s", path=path, repo=reponame) if reponame \ 
     3    else _("ChangeLog for %(path)s", path=path)} 
    34#  
    45# ${_('Generated by Trac %(version)s', version=trac.version)} 
    56# ${format_datetime()} 
     
    1415{%       end %}\ 
    1516{%     end %}\ 
    1617 
    17 ${verbose and extra.message or shorten_line(extra.message)} 
     18${extra.message if verbose else shorten_line(extra.message)} 
    1819 
    1920 
    2021{%   end %}\ 
  • trac/versioncontrol/templates/sortable_th.html

    diff --git a/trac/versioncontrol/templates/sortable_th.html b/trac/versioncontrol/templates/sortable_th.html
    a b  
    1414<html xmlns="http://www.w3.org/1999/xhtml" 
    1515    xmlns:py="http://genshi.edgewall.org/" 
    1616    xmlns:xi="http://www.w3.org/2001/XInclude" py:strip=""> 
    17   <th class="$class_${order == class_ and (desc and ' desc' or ' asc') or ''}"> 
     17  <th class="$class_${(' desc' if desc else ' asc') if order == class_ else None}"> 
    1818    <a title="${_('Sort by %(col)s %(direction)s', col=class_,  
    19                   direction=(order == class_ and not desc  
    20                              and _('(descending)') or _('(ascending)')))}" 
    21       href="${href.browser(reponame, path, rev=stickyrev, order=(class_ != 'name' and class_ or None), 
    22       desc=(class_ == order and not desc and 1 or None))}">$title</a> 
     19                  direction=_('(descending)') if order == class_ and not desc else _('(ascending)'))}" 
     20      href="${href.browser(reponame, path, rev=stickyrev, order=class_ if class_ != 'name' else None, 
     21                           desc=1 if class_ == order and not desc else None)}">$title</a> 
    2322  </th> 
    2423</html> 
  • trac/versioncontrol/web_ui/browser.py

    diff --git a/trac/versioncontrol/web_ui/browser.py b/trac/versioncontrol/web_ui/browser.py
    a b class WikiPropertyRenderer(Component): 
    130130        (''since 0.11'')""") 
    131131 
    132132    def match_property(self, name, mode): 
    133         return (name in self.wiki_properties or \ 
    134                 name in self.oneliner_properties) and 4 or 0 
     133        return 4 if name in self.wiki_properties \ 
     134                    or name in self.oneliner_properties else 0 
    135135 
    136136    def render_property(self, name, mode, context, props): 
    137137        if name in self.wiki_properties: 
    class BrowserModule(Component): 
    258258            # Get three ints out of a `rgb` string or return `default` 
    259259            try: 
    260260                t = tuple([int(v) for v in re.split(r'(\d+)', rgb)[1::2]]) 
    261                 return len(t) == 3 and t or default 
     261                return t if len(t) == 3 else default 
    262262            except ValueError: 
    263263                return default 
    264264         
    class BrowserModule(Component): 
    355355        if reponame and reponame != repos.reponame: # Redirect alias 
    356356            qs = req.query_string 
    357357            req.redirect(req.href.browser(repos.reponame or None, path) 
    358                          + (qs and '?' + qs or '')) 
    359         reponame = repos and repos.reponame or None 
     358                         + ('?' + qs if qs else '')) 
     359        reponame = repos.reponame if repos else None 
    360360         
    361361        # Find node for the requested path/rev 
    362362        context = web_context(req) 
    class BrowserModule(Component): 
    410410            'created_rev': node and node.created_rev, 
    411411            'properties': properties_data, 
    412412            'path_links': path_links, 
    413             'order': order, 'desc': desc and 1 or None, 
     413            'order': order, 'desc': 1 if desc else None, 
    414414            'repo': repo_data, 'dir': dir_data, 'file': file_data, 
    415415            'quickjump_entries': quickjump_data, 
    416416            'wiki_format_messages': \ 
    class BrowserModule(Component): 
    525525        # Ordering of repositories 
    526526        if order == 'date': 
    527527            def repo_order((reponame, repoinfo, repos, youngest, err, href)): 
    528                 return (youngest and youngest.date or to_datetime(0), 
     528                return (youngest.date if youngest else to_datetime(0), 
    529529                        embedded_numbers(reponame.lower())) 
    530530        elif order == 'author': 
    531531            def repo_order((reponame, repoinfo, repos, youngest, err, href)): 
    532                 return (youngest and youngest.author.lower() or '', 
     532                return (youngest.author.lower() if youngest else '', 
    533533                        embedded_numbers(reponame.lower())) 
    534534        else: 
    535535            def repo_order((reponame, repoinfo, repos, youngest, err, href)): 
    class BrowserModule(Component): 
    592592            def file_order(a): 
    593593                return embedded_numbers(a.name.lower()) 
    594594 
    595         dir_order = desc and 1 or -1 
     595        dir_order = 1 if desc else -1 
    596596 
    597597        def browse_order(a): 
    598             return a.isdir and dir_order or 0, file_order(a) 
     598            return dir_order if a.isdir else 0, file_order(a) 
    599599        entries = sorted(entries, key=browse_order, reverse=desc) 
    600600 
    601601        # ''Zip Archive'' alternate link 
    class BrowserModule(Component): 
    630630        if format in ('raw', 'txt'): 
    631631            req.send_response(200) 
    632632            req.send_header('Content-Type', 
    633                             format == 'txt' and 'text/plain' or mime_type) 
     633                            'text/plain' if format == 'txt' else mime_type) 
    634634            req.send_header('Content-Length', node.content_length) 
    635635            req.send_header('Last-Modified', http_date(node.last_modified)) 
    636636            if rev is None: 
    class BrowserModule(Component): 
    877877            add_stylesheet(formatter.req, 'common/css/browser.css') 
    878878            wiki_format_messages = self.config['changeset'] \ 
    879879                                       .getbool('wiki_format_messages') 
    880             data = {'repo': repo, 'order': order, 'desc': desc and 1 or None, 
     880            data = {'repo': repo, 'order': order, 'desc': 1 if desc else None, 
    881881                    'reponame': None, 'path': '/', 'stickyrev': None, 
    882882                    'wiki_format_messages': wiki_format_messages} 
    883883            from trac.web.chrome import Chrome 
  • trac/versioncontrol/web_ui/changeset.py

    diff --git a/trac/versioncontrol/web_ui/changeset.py b/trac/versioncontrol/web_ui/changeset.py
    a b class ChangesetModule(Component): 
    488488        def node_info(node, annotated): 
    489489            href = req.href.browser( 
    490490                reponame, node.created_path, rev=node.created_rev, 
    491                 annotate=annotated and 'blame' or None) 
     491                annotate='blame' if annotated else None) 
    492492            title = _('Show revision %(rev)s of this file in browser', 
    493493                      rev=display_rev(node.rev)) 
    494494            return {'path': node.path, 'rev': node.rev, 
    class ChangesetModule(Component): 
    628628                        'new': new_node and node_info(new_node, annotated), 
    629629                        'props': props, 
    630630                        'diffs': diffs} 
    631                 files.append(new_node and new_node.path or \ 
    632                              old_node and old_node.path or '') 
     631                files.append(new_node.path if new_node else \ 
     632                             old_node.path if old_node else '') 
    633633                filestats[change] += 1 
    634634                if change in Changeset.DIFF_CHANGES: 
    635635                    if chgset: 
    class ChangesetModule(Component): 
    10051005        if reponame or len(repos_for_uid) > 1: 
    10061006            title = ngettext('Changeset in %(repo)s ', 
    10071007                             'Changesets in %(repo)s ', 
    1008                              single and 1 or 2, repo=', '.join(repos_for_uid)) 
     1008                             1 if single else 2, repo=', '.join(repos_for_uid)) 
    10091009        else: 
    1010             title = ngettext('Changeset ', 'Changesets ', single and 1 or 2) 
     1010            title = ngettext('Changeset ', 'Changesets ', 1 if single else 2) 
    10111011        drev_a = older_cset.repos.display_rev(rev_a) 
    10121012        if single: 
    10131013            title = tag(title, tag.em('[%s]' % drev_a)) 
    class ChangesetModule(Component): 
    10451045            r"(?:\b|!)r\d+\b(?!:\d)(?:/[a-zA-Z0-9_/+-]+)?", 
    10461046            lambda x, y, z: 
    10471047            self._format_changeset_link(x, 'changeset', 
    1048                                         y[0] == 'r' and y[1:] or y[1:-1], 
     1048                                        y[1:] if y[0] == 'r' else y[1:-1], 
    10491049                                        y, z)) 
    10501050 
    10511051    def get_link_resolvers(self): 
    class AnyDiffModule(Component): 
    11941194                               if repos.is_viewable(req.perm)) 
    11951195 
    11961196            elem = tag.ul( 
    1197                 [tag.li(isdir and tag.b(path) or path) 
     1197                [tag.li(tag.b(path) if isdir else path) 
    11981198                 for (isdir, name, path) in sorted(entries, key=kind_order) 
    11991199                 if name.lower().startswith(prefix)]) 
    12001200 
  • trac/versioncontrol/web_ui/log.py

    diff --git a/trac/versioncontrol/web_ui/log.py b/trac/versioncontrol/web_ui/log.py
    a b class LogModule(Component): 
    9696        if reponame != repos.reponame:  # Redirect alias 
    9797            qs = req.query_string 
    9898            req.redirect(req.href.log(repos.reponame or None, path) 
    99                          + (qs and '?' + qs or '')) 
     99                         + ('?' + qs if qs else '')) 
    100100 
    101101        normpath = repos.normalize_path(path) 
    102102        # if `revs` parameter is given, then we're restricted to the  
    class LogModule(Component): 
    263263                files = [] 
    264264                actions = [] 
    265265                for cpath, kind, chg, bpath, brev in changeset.get_changes(): 
    266                     files.append(chg == Changeset.DELETE and bpath or cpath) 
     266                    files.append(bpath if chg == Changeset.DELETE else cpath) 
    267267                    actions.append(chg) 
    268268                cs['files'] = files 
    269269                cs['actions'] = actions 
  • trac/versioncontrol/web_ui/util.py

    diff --git a/trac/versioncontrol/web_ui/util.py b/trac/versioncontrol/web_ui/util.py
    a b def get_changes(repos, revs, log=None): 
    4848def get_path_links(href, reponame, path, rev, order=None, desc=None): 
    4949    desc = desc or None 
    5050    links = [{'name': 'source:', 
    51               'href': href.browser(rev=reponame == '' and rev or None, 
     51              'href': href.browser(rev=rev if reponame == '' else None, 
    5252                                   order=order, desc=desc)}] 
    5353    if reponame: 
    5454        links.append({ 
  • trac/web/chrome.py

    diff --git a/trac/web/chrome.py b/trac/web/chrome.py
    a b  
    1414# 
    1515# Author: Christopher Lenz <cmlenz@gmx.de> 
    1616 
    17 from __future__ import with_statement 
    18  
    1917"""Content presentation for the web layer. 
    2018 
    2119The Chrome module deals with delivering and shaping content to the end user, 
    mostly targeting (X)HTML generation but  
    2321web content are also using facilities provided here. 
    2422""" 
    2523 
     24from __future__ import with_statement 
     25 
    2626import datetime 
    2727from functools import partial 
    2828import itertools 
    def prevnext_nav(req, prev_label, next_l 
    226226                          class_='prev') 
    227227         
    228228    add_ctxtnav(req, tag.span(Markup('&larr; '), prev_link or prev_label, 
    229                               class_=not prev_link and 'missing' or None)) 
     229                              class_='missing' if not prev_link else None)) 
    230230 
    231231    if up_label and 'up' in links: 
    232232        up = links['up'][0] 
    def prevnext_nav(req, prev_label, next_l 
    238238                          class_='next') 
    239239 
    240240    add_ctxtnav(req, tag.span(next_link or next_label, Markup(' &rarr;'), 
    241                               class_=not next_link and 'missing' or None)) 
     241                              class_='missing' if not next_link else None)) 
    242242 
    243243 
    244244def web_context(req, resource=None, id=False, version=False, parent=False, 
    def web_context(req, resource=None, id=F 
    267267    :rtype: `RenderingContext` 
    268268    """ 
    269269    if req: 
    270         href = absurls and req.abs_href or req.href 
     270        href = req.abs_href if absurls else req.href 
    271271        perm = req.perm 
    272272    else: 
    273273        href = None 
    class Chrome(Component): 
    728728                # Like 'trac_banner.png' 
    729729                logo_src_abs = abs_href.chrome('common', logo_src) 
    730730                logo_src = href.chrome('common', logo_src) 
    731             width = self.logo_width > -1 and self.logo_width or None 
    732             height = self.logo_height > -1 and self.logo_height or None 
     731            width = self.logo_width if self.logo_width > -1 else None 
     732            height = self.logo_height if self.logo_height > -1 else None 
    733733            logo = { 
    734734                'link': self.logo_link, 'src': logo_src, 
    735735                'src_abs': logo_src_abs, 'alt': self.logo_alt, 
    class Chrome(Component): 
    747747        } 
    748748         
    749749        href = req and req.href 
    750         abs_href = req and req.abs_href or self.env.abs_href 
     750        abs_href = req.abs_href if req else self.env.abs_href 
    751751        admin_href = None 
    752752        if self.env.project_admin_trac_url == '.': 
    753753            admin_href = href 
    class Chrome(Component): 
    794794            return get_resource_url(self.env, resource, abs_href, **kwargs) 
    795795 
    796796        d.update({ 
    797             'context': req and web_context(req) or None, 
     797            'context': web_context(req) if req else None, 
    798798            'Resource': Resource, 
    799799            'url_of': get_rel_url, 
    800800            'abs_url_of': get_abs_url, 
    class Chrome(Component): 
    805805            'abs_href': abs_href, 
    806806            'href': href, 
    807807            'perm': req and req.perm, 
    808             'authname': req and req.authname or '<trac>', 
     808            'authname': req.authname if req else '<trac>', 
    809809            'locale': req and req.locale, 
    810810            'show_email_addresses': show_email_addresses, 
    811811            'show_ip_addresses': self.show_ip_addresses, 
  • trac/web/href.py

    diff --git a/trac/web/href.py b/trac/web/href.py
    a b class Href(object): 
    170170 
    171171        # assemble the query string 
    172172        for k, v in kw.items(): 
    173             add_param(k.endswith('_') and k[:-1] or k, v) 
     173            add_param(k[:-1] if k.endswith('_') else k, v) 
    174174        if params: 
    175175            href += '?' + unicode_urlencode(params, self.query_safe) 
    176176 
  • trac/web/main.py

    diff --git a/trac/web/main.py b/trac/web/main.py
    a b def dispatch_request(environ, start_resp 
    425425        env_error = e 
    426426 
    427427    req = Request(environ, start_response) 
    428     translation.make_activable(lambda: req.locale, env and env.path or None) 
     428    translation.make_activable(lambda: req.locale, env.path if env else None) 
    429429    try: 
    430430        return _dispatch_request(req, env, env_error) 
    431431    finally: 
  • trac/web/standalone.py

    diff --git a/trac/web/standalone.py b/trac/web/standalone.py
    a b def main(): 
    315315                from trac.web.fcgi_frontend import FlupMiddleware 
    316316                flup_app = FlupMiddleware(flup_app) 
    317317            ret = server_cls(flup_app, bindAddress=server_address).run() 
    318             sys.exit(ret and 42 or 0) # if SIGHUP exit with status 42 
     318            sys.exit(42 if ret else 0) # if SIGHUP exit with status 42 
    319319 
    320320    try: 
    321321        if options.daemonize: 
  • trac/web/tests/session.py

    diff --git a/trac/web/tests/session.py b/trac/web/tests/session.py
    a b def _prep_session_table(env, spread_visi 
    2121        db("DELETE FROM session") 
    2222        db("DELETE FROM session_attribute") 
    2323    last_visit_base = time.mktime(datetime(2010, 1, 1).timetuple()) 
    24     visit_delta = spread_visits and 86400 or 0 
     24    visit_delta = 86400 if spread_visits else 0 
    2525    auth_list, anon_list = [], [] 
    2626    with env.db_transaction as db: 
    2727        for x in xrange(20): 
  • trac/wiki/formatter.py

    diff --git a/trac/wiki/formatter.py b/trac/wiki/formatter.py
    a b class WikiProcessor(object): 
    286286            raise ProcessorError(_("!#%(name)s must contain at least one table" 
    287287                                   " cell (and table cells only)", 
    288288                                   name=self.name)) 
    289         return Markup(match.group(self.name == 'table' and 1 or 2)) 
     289        return Markup(match.group(1 if self.name == 'table' else 2)) 
    290290 
    291291    def _format_row(self, env, context, text): 
    292292        if text: 
    class Formatter(object): 
    539539    # HTML escape of &, < and > 
    540540 
    541541    def _htmlescape_formatter(self, match, fullmatch): 
    542         return match == "&" and "&amp;" or match == "<" and "&lt;" or "&gt;" 
     542        return "&amp;" if match == "&" else "&lt;" if match == "<" else "&gt;" 
    543543 
    544544    # Short form (shref) and long form (lhref) of TracLinks 
    545545 
    class Formatter(object): 
    837837            self.close_indentation() # FIXME: why not lists in quotes? 
    838838            self._list_stack.append((new_type, depth)) 
    839839            self._set_tab(depth) 
    840             class_attr = (lclass and ' class="%s"' % lclass) or '' 
    841             start_attr = (start and ' start="%s"' % start) or '' 
    842             self.out.write('<'+new_type+class_attr+start_attr+'><li>') 
     840            class_attr = ' class="%s"' % lclass if lclass else '' 
     841            start_attr = ' start="%s"' % start if start else '' 
     842            self.out.write('<' + new_type + class_attr + start_attr + '><li>') 
    843843        def close_item(): 
    844844            self.flush_tags() 
    845845            self.out.write('</li>') 
    class Formatter(object): 
    877877    # Definition Lists 
    878878 
    879879    def _definition_formatter(self, match, fullmatch): 
    880         tmp = self.in_def_list and '</dd>' or '<dl class="wiki">' 
     880        tmp = '</dd>' if self.in_def_list else '<dl class="wiki">' 
    881881        definition = match[:match.find('::')] 
    882882        tmp += '<dt>%s</dt><dd>' % format_to_oneliner(self.env, self.context, 
    883883                                                      definition) 
    class Formatter(object): 
    901901                        self.in_list_item = True 
    902902                        self._set_list_depth(idepth) 
    903903                        return '' 
    904             elif idepth <= ldepth + (ltype == 'ol' and 3 or 2): 
     904            elif idepth <= ldepth + (3 if ltype == 'ol' else 2): 
    905905                self.in_list_item = True 
    906906                return '' 
    907907        if not self.in_def_list: 
    class Formatter(object): 
    913913 
    914914    def _get_quote_depth(self): 
    915915        """Return the space offset associated to the deepest opened quote.""" 
    916         return self._quote_stack and self._quote_stack[-1] or 0 
     916        return self._quote_stack[-1] if self._quote_stack else 0 
    917917 
    918918    def _set_quote_depth(self, depth, citation=False): 
    919919        def open_quote(depth): 
    class Formatter(object): 
    923923            def open_one_quote(d): 
    924924                self._quote_stack.append(d) 
    925925                self._set_tab(d) 
    926                 class_attr = citation and ' class="citation"' or '' 
     926                class_attr = ' class="citation"' if citation else '' 
    927927                self.out.write('<blockquote%s>' % class_attr + os.linesep) 
    928928            if citation: 
    929929                for d in range(quote_depth+1, depth+1): 
    class Formatter(object): 
    10701070        args = WikiParser._processor_param_re.split(line) 
    10711071        del args[::3] 
    10721072        keys = [str(k) for k in args[::2]] # used as keyword parameters 
    1073         values = [(v and v[0] in '"\'' and [v[1:-1]] or [v])[0] 
     1073        values = [v[1:-1] if v[:1] + v[-1:] in ('""', "''") else v 
    10741074                  for v in args[1::2]] 
    10751075        return dict(zip(keys, values)) 
    10761076 
    class OneLinerFormatter(Formatter): 
    13231323            return '' 
    13241324        else: 
    13251325            args = fullmatch.group('macroargs') 
    1326             return '[[%s%s]]' % (name,  args and '(...)' or '') 
     1326            return '[[%s%s]]' % (name, '(...)' if args else '') 
    13271327 
    13281328    def format(self, text, out, shorten=False): 
    13291329        if not text: 
  • trac/wiki/intertrac.py

    diff --git a/trac/wiki/intertrac.py b/trac/wiki/intertrac.py
    a b class InterTracDispatcher(Component): 
    8383        parts = link.split(':', 1) 
    8484        if len(parts) > 1: 
    8585            resolver, target = parts 
    86             if target and (target[0] not in '\'"' or target[0] != target[-1]): 
     86            if target[:1] + target[-1:] not in ('""', "''"): 
    8787                link = '%s:"%s"' % (resolver, target) 
    8888        from trac.web.chrome import web_context 
    8989        link_frag = extract_link(self.env, web_context(req), link) 
  • trac/wiki/interwiki.py

    diff --git a/trac/wiki/interwiki.py b/trac/wiki/interwiki.py
    a b class InterWikiMap(Component): 
    6868        """Replace "$1" by the first args, "$2" by the second, etc.""" 
    6969        def setarg(match): 
    7070            num = int(match.group()[1:]) 
    71             return 0 < num <= len(args) and args[num-1] or '' 
     71            return args[num - 1] if 0 < num <= len(args) else '' 
    7272        return re.sub(InterWikiMap._argspec_re, setarg, txt) 
    7373 
    7474    def _expand_or_append(self, txt, args): 
    class InterWikiMap(Component): 
    7676        if not args: 
    7777            return txt 
    7878        expanded = self._expand(txt, args) 
    79         return expanded == txt and txt + args[0] or expanded 
     79        return txt + args[0] if expanded == txt else expanded 
    8080 
    8181    def url(self, ns, target): 
    8282        """Return `(url, title)` for the given InterWiki `ns`. 
    class InterWikiMap(Component): 
    8484        Expand the colon-separated `target` arguments. 
    8585        """ 
    8686        ns, url, title = self[ns] 
    87         maxargnum = max([0]+[int(a[1:]) for a in 
    88                              re.findall(InterWikiMap._argspec_re, url)]) 
     87        maxargnum = max([0] + [int(a[1:]) for a in 
     88                               re.findall(InterWikiMap._argspec_re, url)]) 
    8989        target, query, fragment = split_url_into_path_query_fragment(target) 
    9090        if maxargnum > 0: 
    9191            args = target.split(':', (maxargnum - 1)) 
    class InterWikiMap(Component): 
    141141                    if m: 
    142142                        prefix, url, title = m.groups() 
    143143                        url = url.strip() 
    144                         title = title and title.strip() or prefix 
     144                        title = title.strip() if title else prefix 
    145145                        map[prefix.upper()] = (prefix, url, title) 
    146146            elif line.startswith('----'): 
    147147                in_map = True 
    class InterWikiMap(Component): 
    168168            interwikis.append({ 
    169169                'prefix': prefix, 'url': url, 'title': title, 
    170170                'rc_url': self._expand_or_append(url, ['RecentChanges']), 
    171                 'description': title == prefix and url or title}) 
     171                'description': url if title == prefix else title}) 
    172172 
    173173        return tag.table(tag.tr(tag.th(tag.em("Prefix")), 
    174174                                tag.th(tag.em("Site"))), 
  • trac/wiki/macros.py

    diff --git a/trac/wiki/macros.py b/trac/wiki/macros.py
    a b class WikiMacroBase(Component): 
    5454    def get_macro_description(self, name): 
    5555        """Return the subclass's docstring.""" 
    5656        doc = inspect.getdoc(self.__class__) 
    57         return doc and to_unicode(doc) or '' 
     57        return to_unicode(doc) if doc else '' 
    5858 
    5959    def parse_macro(self, parser, name, content): 
    6060        raise NotImplementedError 
    class TitleIndexMacro(WikiMacroBase): 
    103103 
    104104    def expand_macro(self, formatter, name, content): 
    105105        args, kw = parse_args(content) 
    106         prefix = args and args[0].strip() or None 
     106        prefix = args[0].strip() if args else None 
    107107        hideprefix = args and len(args) > 1 and args[1].strip() == 'hideprefix' 
    108108        minsize = max(int(kw.get('min', 2)), 2) 
    109109        depth = int(kw.get('depth', -1)) 
    110         start = prefix and prefix.count('/') or 0 
     110        start = prefix.count('/') if prefix else 0 
    111111        format = kw.get('format', '') 
    112112 
    113113        def parse_list(name): 
    class TitleIndexMacro(WikiMacroBase): 
    175175            groups = [] 
    176176 
    177177            for key, grouper in groupby(entries, lambda (elts, name): 
    178                                                 elts and elts[0] or ''): 
     178                                                    elts[0] if elts else ''): 
    179179                # remove key from path_elements in grouped entries for further 
    180180                # grouping 
    181181                grouped_entries = [(path_elements[1:], page_name) 
    class MacroListMacro(WikiMacroBase): 
    567567    def expand_macro(self, formatter, name, content): 
    568568        from trac.wiki.formatter import system_message 
    569569 
    570         content = content and content.strip() or '' 
     570        content = content.strip() if content else '' 
    571571        name_filter = content.strip('*') 
    572572 
    573573        def get_macro_descr(): 
  • trac/wiki/model.py

    diff --git a/trac/wiki/model.py b/trac/wiki/model.py
    a b class WikiPage(object): 
    6868            self.time = from_utimestamp(time) 
    6969            self.text = text 
    7070            self.comment = comment 
    71             self.readonly = readonly and int(readonly) or 0 
     71            self.readonly = int(readonly) if readonly else 0 
    7272            break 
    7373        else: 
    7474            self.version = 0 
  • trac/wiki/templates/wiki_edit.html

    diff --git a/trac/wiki/templates/wiki_edit.html b/trac/wiki/templates/wiki_edit.html
    a b  
    6363 
    6464  <body> 
    6565    <div id="content" class="wiki" 
    66        py:with="preview_or_review = action == 'preview' and (not diff or changes[0].diffs)"> 
     66         py:with="preview_or_review = action == 'preview' and (not diff or changes[0].diffs)"> 
    6767      <div class="trac-topnav" py:if="sidebyside or preview_or_review" py:choose=""> 
    6868        <a py:when="sidebyside" href="#changeinfo" 
    69           title="Go to Save, Preview, Review or Cancel buttons">Actions</a> 
     69           title="Go to Save, Preview, Review or Cancel buttons">Actions</a> 
    7070        <a py:when="diff" href="#info" title="See the diffs">Review</a> 
    7171        <a py:otherwise="" href="#info" title="See the preview">Preview</a> 
    7272        &darr; 
  • trac/wiki/templates/wiki_edit_form.html

    diff --git a/trac/wiki/templates/wiki_edit_form.html b/trac/wiki/templates/wiki_edit_form.html
    a b  
    2626        </label> 
    2727        <input type="checkbox" name="sidebyside" id="sidebyside" checked="$sidebyside" /> 
    2828      </div> 
    29       <p><textarea id="text" class="wikitext${not sidebyside and ' trac-resizable' or ''}" name="text" cols="80" rows="$edit_rows"> 
     29      <p><textarea id="text" class="wikitext${' trac-resizable' if not sidebyside else None}" 
     30                   name="text" cols="80" rows="$edit_rows"> 
    3031$page.text</textarea> 
    3132      </p> 
    3233      <div id="help" i18n:msg=""> 
  • trac/wiki/templates/wiki_view.html

    diff --git a/trac/wiki/templates/wiki_view.html b/trac/wiki/templates/wiki_view.html
    a b  
    8888                      <div py:if="templates" id="template"> 
    8989                        <label for="template">Using the template:</label> 
    9090                        <select name="template"> 
    91                           <option selected="${not default_template in templates and 'selected' or None}" 
     91                          <option selected="${not default_template in templates or None}" 
    9292                                  value="">(blank page)</option> 
    9393                          <option py:for="t in sorted(templates)" value="$t" 
    9494                                  selected="${t == default_template or None}">$t</option> 
  • trac/wiki/tests/formatter.py

    diff --git a/trac/wiki/tests/formatter.py b/trac/wiki/tests/formatter.py
    a b class SampleResolver(Component): 
    9595    def _format_link(self, formatter, ns, target, label): 
    9696        kind, module = 'text', 'stuff' 
    9797        try: 
    98             kind = int(target) % 2 and 'odd' or 'even' 
     98            kind = 'odd' if int(target) % 2 else 'even' 
    9999            module = 'thing' 
    100100        except ValueError: 
    101101            pass 
  • trac/wiki/web_ui.py

    diff --git a/trac/wiki/web_ui.py b/trac/wiki/web_ui.py
    a b class WikiModule(Component): 
    234234                    # TRANSLATOR: wiki page 
    235235                    'rev': v or _('currently edited'),  
    236236                    'shortrev': v or last + 1, 
    237                     'href': v and req.href.wiki(page.name, version=v) or None} 
     237                    'href': req.href.wiki(page.name, version=v) if v else None} 
    238238        changes = [{'diffs': diffs, 'props': [], 
    239239                    'new': version_info(new_version, old_version), 
    240240                    'old': version_info(old_version)}] 
    class WikiModule(Component): 
    314314                          new_name, old_version, old_name, new_name) 
    315315                redirection.save(author, comment, req.remote_addr) 
    316316         
    317         req.redirect(req.href.wiki(redirect and old_name or new_name)) 
     317        req.redirect(req.href.wiki(old_name if redirect else new_name)) 
    318318 
    319319    def _do_save(self, req, page): 
    320320        if page.readonly: 
    class WikiModule(Component): 
    351351            version = int(req.args.get('version', 0)) 
    352352        old_version = int(req.args.get('old_version') or 0) or version 
    353353 
    354         what = ((version and old_version and version - old_version > 1) and 
    355                'multiple') or version and 'single' or 'page' 
     354        what = 'multiple' if version and old_version \ 
     355                             and version - old_version > 1 \ 
     356               else 'single' if version else 'page' 
    356357 
    357358        num_versions = 0 
    358359        new_date = None 
    class WikiModule(Component): 
    382383            req.perm(page.resource).require('WIKI_RENAME') 
    383384            
    384385        data = self._page_data(req, page, 'rename') 
    385         data['new_name'] = new_name is None and page.name or new_name 
     386        data['new_name'] = new_name if new_name is not None else page.name 
    386387        self._wiki_ctxtnav(req, page) 
    387388        return 'wiki_rename.html', data, None 
    388389         
    class WikiModule(Component): 
    526527            'attachments': AttachmentModule(self.env).attachment_data(context), 
    527528        }) 
    528529        if action in ('diff', 'merge'): 
    529             old_text = original_text and original_text.splitlines() or [] 
    530             new_text = page.text and page.text.splitlines() or [] 
     530            old_text = original_text.splitlines() if original_text else [] 
     531            new_text = page.text.splitlines() if page.text else [] 
    531532            diff_data, changes = self._prepare_diff( 
    532533                req, page, old_text, new_text, page.version, '') 
    533534            data.update({'diff': diff_data, 'changes': changes, 
  • tracopt/mimeview/enscript.py

    diff --git a/tracopt/mimeview/enscript.py b/tracopt/mimeview/enscript.py
    a b class EnscriptRenderer(Component): 
    151151        i = odata.find('<PRE>') 
    152152        beg = i > 0 and i + 6 
    153153        i = odata.rfind('</PRE>') 
    154         end = i > 0 and i or len(odata) 
     154        end = i if i > 0 else len(odata) 
    155155 
    156156        odata = EnscriptDeuglifier().format(odata[beg:end].decode('utf-8')) 
    157157        return [Markup(line) for line in odata.splitlines()] 
  • tracopt/perm/authz_policy.py

    diff --git a/tracopt/perm/authz_policy.py b/tracopt/perm/authz_policy.py
    a b class AuthzPolicy(Component): 
    169169 
    170170    def get_authz_file(self): 
    171171        f = self.authz_file 
    172         return os.path.isabs(f) and f or os.path.join(self.env.path, f) 
     172        return f if os.path.isabs(f) else os.path.join(self.env.path, f) 
    173173 
    174174    def parse_authz(self): 
    175175        self.log.debug('Parsing authz security policy %s', 
  • tracopt/perm/config_perm_provider.py

    diff --git a/tracopt/perm/config_perm_provider.py b/tracopt/perm/config_perm_provider.py
    a b class ExtraPermissionsProvider(Component 
    5151            meta = meta.strip().upper() 
    5252            if meta and not meta.startswith('_'): 
    5353                permissions.setdefault(meta, []).extend(perms) 
    54         return [v and (k, v) or k for k, v in permissions.iteritems()] 
     54        return [(k, v) if v else k for k, v in permissions.iteritems()]