[Checkins] SVN: Products.CMFCalendar/trunk/Products/CMFCalendar/ code cleanup:

Yvo Schubbe cvs-admin at zope.org
Tue Apr 24 10:35:37 UTC 2012


Log message for revision 125264:
  code cleanup:
  - replaced has_key
  - replaced oldstyle errors
  - PEP 8

Changed:
  U   Products.CMFCalendar/trunk/Products/CMFCalendar/CalendarTool.py
  U   Products.CMFCalendar/trunk/Products/CMFCalendar/Event.py

-=-
Modified: Products.CMFCalendar/trunk/Products/CMFCalendar/CalendarTool.py
===================================================================
--- Products.CMFCalendar/trunk/Products/CMFCalendar/CalendarTool.py	2012-04-23 22:00:00 UTC (rev 125263)
+++ Products.CMFCalendar/trunk/Products/CMFCalendar/CalendarTool.py	2012-04-24 10:35:32 UTC (rev 125264)
@@ -51,7 +51,7 @@
     """ A tool for encapsulating how calendars work and are displayed """
 
     id = 'portal_calendar'
-    meta_type= 'CMF Calendar Tool'
+    meta_type = 'CMF Calendar Tool'
     security = ClassSecurityInfo()
 
     implements(ICalendarTool)
@@ -61,9 +61,10 @@
     use_session = False
     firstweekday = 6 # 6 is Sunday
 
-    manage_options = (({'label' : 'Overview', 'action' : 'manage_overview'},
-                       {'label' : 'Configure', 'action' : 'manage_configure'},
-                      ) + SimpleItem.manage_options)
+    manage_options = (
+        ({'label': 'Overview', 'action': 'manage_overview'},
+         {'label': 'Configure', 'action': 'manage_configure'}) +
+        SimpleItem.manage_options)
 
     #
     #   ZMI methods
@@ -79,7 +80,7 @@
     security.declareProtected(ManagePortal, 'edit_configuration')
     def edit_configuration(self, show_types, use_session, show_states=None,
                            firstweekday=None, REQUEST=None):
-        """ Change the configuration of the calendar tool 
+        """ Change the configuration of the calendar tool
         """
         self.calendar_types = tuple(show_types)
         self.use_session = bool(use_session)
@@ -116,25 +117,25 @@
 
     security.declarePublic('getCalendarTypes')
     def getCalendarTypes(self):
-        """ Returns a list of type that will show in the calendar 
+        """ Returns a list of type that will show in the calendar
         """
         return self.calendar_types
 
     security.declarePublic('getCalendarStates')
     def getCalendarStates(self):
-        """ Returns a list of workflow states that will show in the calendar 
+        """ Returns a list of workflow states that will show in the calendar
         """
         return self.calendar_states
 
     security.declarePublic('getUseSession')
     def getUseSession(self):
-        """ Returns the Use_Session option 
+        """ Returns the Use_Session option
         """
         return bool(self.use_session)
 
     security.declarePublic('getDays')
     def getDays(self):
-        """ Returns a list of days with the correct start day first 
+        """ Returns a list of days with the correct start day first
         """
         return self._getCalendar().weekheader(2).split()
 
@@ -176,10 +177,10 @@
         for week in daysByWeek:
             days = []
             for day in week:
-                if events.has_key(day):
+                if day in events:
                     days.append(events[day])
                 else:
-                    days.append({'day': day, 'event': 0, 'eventslist':[]})
+                    days.append({'day': day, 'event': 0, 'eventslist': []})
 
             weeks.append(days)
 
@@ -187,7 +188,7 @@
 
     security.declarePublic('catalog_getevents')
     def catalog_getevents(self, year, month):
-        """ given a year and month return a list of days that have events 
+        """ given a year and month return a list of days that have events
         """
         year = int(year)
         month = int(month)
@@ -201,10 +202,10 @@
                         review_state=self.getCalendarStates(),
                         start={'query': last_date, 'range': 'max'},
                         end={'query': first_date, 'range': 'min'},
-                        sort_on='start' )
+                        sort_on='start')
 
         # compile a list of the days that have events
-        eventDays={}
+        eventDays = {}
         for daynumber in range(1, 32): # 1 to 31
             eventDays[daynumber] = {'eventslist': [],
                                     'event': 0,
@@ -215,7 +216,7 @@
                 break
             else:
                 includedevents.append(result.getRID())
-            event={}
+            event = {}
             # we need to deal with events that end next month
             if  result.end.greaterThan(last_date):
                 eventEndDay = last_day
@@ -237,31 +238,32 @@
             event['title'] = result.Title or result.getId
 
             if eventStartDay != eventEndDay:
-                allEventDays = range(eventStartDay, eventEndDay+1)
+                allEventDays = range(eventStartDay, eventEndDay + 1)
                 eventDays[eventStartDay]['eventslist'].append(
                         {'end': None,
                          'start': result.start.Time(),
-                         'title': event['title']} )
+                         'title': event['title']})
                 eventDays[eventStartDay]['event'] = 1
 
                 for eventday in allEventDays[1:-1]:
                     eventDays[eventday]['eventslist'].append(
                         {'end': None,
                          'start': None,
-                         'title': event['title']} )
+                         'title': event['title']})
                     eventDays[eventday]['event'] = 1
 
-                if (result.end == result.end.earliestTime() and 
-                    event['end'] is not None): 
+                if (result.end == result.end.earliestTime() and
+                    event['end'] is not None):
                     # ends some day this month at midnight
                     last_day_data = eventDays[allEventDays[-2]]
                     last_days_event = last_day_data['eventslist'][-1]
-                    last_days_event['end'] = (result.end-1).latestTime().Time()
+                    last_days_event['end'] = (result.end
+                                              - 1).latestTime().Time()
                 else:
-                    eventDays[eventEndDay]['eventslist'].append( 
-                        { 'end': event['end'],
-                          'start': None,
-                          'title': event['title']} )
+                    eventDays[eventEndDay]['eventslist'].append(
+                        {'end': event['end'],
+                         'start': None,
+                         'title': event['title']})
                     eventDays[eventEndDay]['event'] = 1
             else:
                 eventDays[eventStartDay]['eventslist'].append(event)
@@ -281,14 +283,13 @@
             B) End on this day  OR
             C) Start before this day  AND  end after this day
         """
-        day, month, year = ( int(thisDay.day())
-                           , int(thisDay.month())
-                           , int(thisDay.year())
-                           )
+        day, month, year = (int(thisDay.day()), int(thisDay.month()),
+                            int(thisDay.year()))
 
         first_date, last_date = self.getBeginAndEndTimes(day, month, year)
         zone = first_date.localZone()
-        after_midnight_str = '%d-%02d-%02d 00:01:00 %s' % (year,month,day,zone)
+        after_midnight_str = '%d-%02d-%02d 00:01:00 %s' % (year, month, day,
+                                                           zone)
         after_midnight = DateTime(after_midnight_str)
 
         # Get all events that Start on this day
@@ -297,21 +298,21 @@
                         portal_type=self.getCalendarTypes(),
                         review_state=self.getCalendarStates(),
                         start={'query': (first_date, last_date),
-                               'range': 'minmax'} )
+                               'range': 'minmax'})
 
         # Get all events that End on this day
         query += ctool(
                          portal_type=self.getCalendarTypes(),
                          review_state=self.getCalendarStates(),
                          end={'query': (after_midnight, last_date),
-                              'range': 'minmax'} )
+                              'range': 'minmax'})
 
         # Get all events that Start before this day AND End after this day
         query += ctool(
                          portal_type=self.getCalendarTypes(),
                          review_state=self.getCalendarStates(),
                          start={'query': first_date, 'range': 'max'},
-                         end={'query': last_date, 'range': 'min'} )
+                         end={'query': last_date, 'range': 'min'})
 
         # Unique the results
         results = unique_results(query)
@@ -366,7 +367,7 @@
     security.declarePublic('getNextEvent')
     def getNextEvent(self, start_date=None):
         """ Get the next event that starts after start_date
-        
+
         start_date is expected to be a DateTime instance
         """
         if start_date is None:

Modified: Products.CMFCalendar/trunk/Products/CMFCalendar/Event.py
===================================================================
--- Products.CMFCalendar/trunk/Products/CMFCalendar/Event.py	2012-04-23 22:00:00 UTC (rev 125263)
+++ Products.CMFCalendar/trunk/Products/CMFCalendar/Event.py	2012-04-24 10:35:32 UTC (rev 125264)
@@ -37,50 +37,47 @@
 from Products.CMFDefault.utils import SimpleHTMLParser
 from Products.GenericSetup.interfaces import IDAVAware
 
-def addEvent( self
-            , id
-            , title=''
-            , description=''
-            , effective_date = None 
-            , expiration_date = None 
-            , start_date = None 
-            , end_date = None
-            , location=''
-            , contact_name=''
-            , contact_email=''
-            , contact_phone=''
-            , event_url=''
-            , REQUEST=None
-            ):
+def addEvent(self,
+             id,
+             title='',
+             description='',
+             effective_date=None,
+             expiration_date=None,
+             start_date=None,
+             end_date=None,
+             location='',
+             contact_name='',
+             contact_email='',
+             contact_phone='',
+             event_url='',
+             REQUEST=None):
     """Create an empty event.
     """
-    event = Event( id
-                 , title
-                 , description
-                 , effective_date
-                 , expiration_date
-                 , start_date
-                 , end_date
-                 , location
-                 , contact_name
-                 , contact_email
-                 , contact_phone
-                 , event_url
-                 )
+    event = Event(id,
+                  title,
+                  description,
+                  effective_date,
+                  expiration_date,
+                  start_date,
+                  end_date,
+                  location,
+                  contact_name,
+                  contact_email,
+                  contact_phone,
+                  event_url)
     self._setObject(id, event, suppress_events=True)
 
-def _dateStrings( when ):
-
+def _dateStrings(when):
     strings = {}
 
     if when is not None:
-        strings[ 'year' ]   = str( when.year() )
-        strings[ 'month' ]  = str( when.month() )
-        strings[ 'day' ]    = str( when.day() )
+        strings['year'] = str(when.year())
+        strings['month'] = str(when.month())
+        strings['day'] = str(when.day())
     else:
-        strings[ 'year' ]   = ''
-        strings[ 'month' ]  = ''
-        strings[ 'day' ]    = ''
+        strings['year'] = ''
+        strings['month'] = ''
+        strings['day'] = ''
 
     return strings
 
@@ -96,20 +93,19 @@
 
     implements(IMutableEvent, IEvent, IDAVAware)
 
-    def __init__( self
-                , id
-                , title=''
-                , description=''
-                , effective_date = None 
-                , expiration_date = None 
-                , start_date = None
-                , end_date = None
-                , location=''
-                , contact_name=''
-                , contact_email=''
-                , contact_phone=''
-                , event_url=''
-                ):
+    def __init__(self,
+                 id,
+                 title='',
+                 description='',
+                 effective_date=None,
+                 expiration_date=None,
+                 start_date=None,
+                 end_date=None,
+                 location='',
+                 contact_name='',
+                 contact_email='',
+                 contact_phone='',
+                 event_url=''):
         DefaultDublinCoreImpl.__init__(self)
         self.id = id
         self.setTitle(title)
@@ -140,13 +136,13 @@
         self.contact_phone = contact_phone
         self.event_url = event_url
 
-    security.declarePrivate( '_datify' )
-    def _datify( self, attrib ):
+    security.declarePrivate('_datify')
+    def _datify(self, attrib):
         if attrib == 'None':
             attrib = None
-        elif not isinstance( attrib, DateTime ):
+        elif not isinstance(attrib, DateTime):
             if attrib is not None:
-                attrib = DateTime( attrib )
+                attrib = DateTime(attrib)
         return attrib
 
     security.declarePublic('getEndStrings')
@@ -166,30 +162,29 @@
         return _dateStrings(self.start())
 
     security.declareProtected(ChangeEvents, 'edit')
-    def edit( self
-            , title=None
-            , description=None
-            , eventType=None
-            , effectiveDay=None
-            , effectiveMo=None
-            , effectiveYear=None
-            , expirationDay=None
-            , expirationMo=None
-            , expirationYear=None
-            , start_time=None
-            , startAMPM=None
-            , stop_time=None
-            , stopAMPM=None
-            , location=None
-            , contact_name=None
-            , contact_email=None
-            , contact_phone=None
-            , event_url=None
-            ):
+    def edit(self,
+             title=None,
+             description=None,
+             eventType=None,
+             effectiveDay=None,
+             effectiveMo=None,
+             effectiveYear=None,
+             expirationDay=None,
+             expirationMo=None,
+             expirationYear=None,
+             start_time=None,
+             startAMPM=None,
+             stop_time=None,
+             stopAMPM=None,
+             location=None,
+             contact_name=None,
+             contact_email=None,
+             contact_phone=None,
+             event_url=None):
         """\
         """
 
-        if title is not None: 
+        if title is not None:
             self.setTitle(title)
         if description is not None:
             self.setDescription(description)
@@ -199,31 +194,27 @@
         start_date = end_date = None
 
         if effectiveDay and effectiveMo and effectiveYear and start_time:
-            efdate = '%s/%s/%s %s %s' % (effectiveYear
-                                         , effectiveMo
-                                         , effectiveDay
-                                         , start_time
-                                         , startAMPM
-                                         )
-            start_date = DateTime( efdate )
+            efdate = '%s/%s/%s %s %s' % (effectiveYear,
+                                         effectiveMo,
+                                         effectiveDay,
+                                         start_time,
+                                         startAMPM)
+            start_date = DateTime(efdate)
 
         if expirationDay and expirationMo and expirationYear and stop_time:
+            exdate = '%s/%s/%s %s %s' % (expirationYear,
+                                         expirationMo,
+                                         expirationDay,
+                                         stop_time,
+                                         stopAMPM)
+            end_date = DateTime(exdate)
 
-            exdate = '%s/%s/%s %s %s' % (expirationYear
-                                         , expirationMo
-                                         , expirationDay
-                                         , stop_time
-                                         , stopAMPM
-                                         )
-            end_date = DateTime( exdate )
-
         if start_date and end_date:
-
             if end_date < start_date:
                 end_date = start_date
 
-            self.setStartDate( start_date )
-            self.setEndDate( end_date )
+            self.setStartDate(start_date)
+            self.setEndDate(end_date)
 
         if location is not None:
             self.location = location
@@ -240,7 +231,7 @@
     security.declarePublic('buildTimes')
     def buildTimes(self):
         result = []
-        for hour in range (1, 13):
+        for hour in range(1, 13):
             for min in (00, 30):
                 result.append('%02d:%02d' % (hour, min))
         return result
@@ -248,14 +239,14 @@
     security.declarePublic('buildDays')
     def buildDays(self):
         result = []
-        for day in range (1, 32):
+        for day in range(1, 32):
             result.append(str('%d' % (day)))
         return result
 
     security.declarePublic('buildMonths')
     def buildMonths(self):
         result = []
-        for month in range (1, 13):
+        for month in range(1, 13):
             result.append(str('%d' % (month)))
         return result
 
@@ -264,7 +255,7 @@
         result = []
         start = (DateTime().year() - 2)
         end = (DateTime().year() + 5)
-        for year in range (start, end):
+        for year in range(start, end):
             result.append(str(year))
         return result
 
@@ -284,27 +275,27 @@
     def start(self):
         """ Return our start time as a DateTime object
         """
-        date = getattr( self, 'start_date', None )
+        date = getattr(self, 'start_date', None)
         return date is None and self.created() or date
 
     security.declarePublic('end')
     def end(self):
         """ Return our end time as a DateTime object
         """
-        date = getattr( self, 'end_date', None )
+        date = getattr(self, 'end_date', None)
         return date is None and self.start() or date
 
     security.declarePublic('getStartTimeString')
-    def getStartTimeString( self ):
+    def getStartTimeString(self):
         """ Return our start time as a string.
         """
-        return self.start().AMPMMinutes() 
+        return self.start().AMPMMinutes()
 
     security.declarePublic('getStopTimeString')
-    def getStopTimeString( self ):
+    def getStopTimeString(self):
         """ Return our stop time as a string.
         """
-        return self.end().AMPMMinutes() 
+        return self.end().AMPMMinutes()
 
     security.declarePrivate('handleText')
     def handleText(self, text, format=None):
@@ -338,21 +329,19 @@
         headers['Subject'] = new_subject or self.Subject()
         new_contrib = contributorsplitter(headers)
         headers['Contributors'] = new_contrib or self.Contributors()
-        haveheader = headers.has_key
         for key, value in self.getMetadataHeaders():
-            if not haveheader(key):
+            if not key in headers:
                 headers[key] = value
         self._editMetadata(title=headers['Title'],
-                          subject=headers['Subject'],
-                          contributors=headers['Contributors'],
-                          effective_date=headers['Effective_date'],
-                          expiration_date=headers['Expiration_date'],
-                          format=headers['Format'],
-                          language=headers['Language'],
-                          rights=headers['Rights'],
-                          )
+                           subject=headers['Subject'],
+                           contributors=headers['Contributors'],
+                           effective_date=headers['Effective_date'],
+                           expiration_date=headers['Expiration_date'],
+                           format=headers['Format'],
+                           language=headers['Language'],
+                           rights=headers['Rights'])
 
-    security.declarePublic( 'getMetadataHeaders' )
+    security.declarePublic('getMetadataHeaders')
     def getMetadataHeaders(self):
         """ Return metadata attributes in RFC-822-style header spec.
         """
@@ -360,7 +349,7 @@
         hdrlist = [x for x in DefaultDublinCoreImpl.getMetadataHeaders(self)
                          if x[0] != 'Description']
         hdrlist.append(('Startdate', self.start().strftime(fmt)))
-        hdrlist.append(('Enddate',  self.end().strftime(fmt)))
+        hdrlist.append(('Enddate', self.end().strftime(fmt)))
         hdrlist.append(('Location', self.location))
         hdrlist.append(('Contactname', self.contact_name))
         hdrlist.append(('Contactemail', self.contact_email))
@@ -380,23 +369,24 @@
         guessedformat = REQUEST.get_header('Content-Type', 'text/plain')
         ishtml = (guessedformat == 'text/html') or html_headcheck(body)
 
-        if ishtml: self.setFormat('text/html')
-        else: self.setFormat('text/plain')
+        if ishtml:
+            self.setFormat('text/html')
+        else:
+            self.setFormat('text/plain')
 
         try:
             headers, body, format = self.handleText(text=body)
             self.setMetadata(headers)
             self.setStartDate(headers['Startdate'])
             self.setEndDate(headers['Enddate'])
-            self.edit( location=headers['Location']
-             , contact_name=headers['Contactname']
-             , contact_email=headers['Contactemail']
-             , contact_phone=headers['Contactphone']
-             , event_url=headers['Eventurl']
-             , description=body
-             )
+            self.edit(location=headers['Location'],
+                      contact_name=headers['Contactname'],
+                      contact_email=headers['Contactemail'],
+                      contact_phone=headers['Contactphone'],
+                      event_url=headers['Eventurl'],
+                      description=body)
 
-        except ResourceLockedError, msg:
+        except ResourceLockedError:
             transaction.abort()
             RESPONSE.setStatus(423)
             return RESPONSE
@@ -409,13 +399,13 @@
     def manage_FTPget(self):
         "Get the document body for FTP download (also used for the WebDAV SRC)"
         hdrlist = self.getMetadataHeaders()
-        hdrtext = formatRFC822Headers( hdrlist )
-        bodytext = '%s\r\n\r\n%s' % ( hdrtext, self.Description() )
+        hdrtext = formatRFC822Headers(hdrlist)
+        bodytext = '%s\r\n\r\n%s' % (hdrtext, self.Description())
 
         return bodytext
 
     security.declareProtected(View, 'get_size')
-    def get_size( self ):
+    def get_size(self):
         """ Used for FTP and apparently the ZMI now too """
         return len(self.manage_FTPget())
 



More information about the checkins mailing list