Browse Source

Add the *with statement* to the Raster classes and add an example in the docstring.

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@55953 15284696-431f-4ddb-bdfa-cd5b030d7da7
Pietro Zambelli 12 years ago
parent
commit
32cafe5b97
2 changed files with 19 additions and 11 deletions
  1. 11 2
      lib/python/pygrass/raster/__init__.py
  2. 8 9
      lib/python/pygrass/raster/abstract.py

+ 11 - 2
lib/python/pygrass/raster/__init__.py

@@ -34,8 +34,6 @@ from raster_type import TYPE as RTYPE, RTYPE_STR
 from buffer import Buffer
 from segment import Segment
 from rowio import RowIO
-from category import Category
-from history import History
 
 
 class RasterRow(RasterAbstractBase):
@@ -101,6 +99,17 @@ class RasterRow(RasterAbstractBase):
          ('bare ground path', 10, None),
          ('grass', 11, None)]
 
+    Open a raster map using the *with statement*: ::
+
+        >>> with RasterRow('elevation') as elev:
+        ...     for row in elev[:3]:
+        ...         print row[:4]
+        ...
+        [ 141.99613953  141.27848816  141.37904358  142.29821777]
+        [ 142.90461731  142.39450073  142.68611145  143.59086609]
+        [ 143.81854248  143.54707336  143.83972168  144.59527588]
+        >>> elev.is_open()
+        False
 
     """
     def __init__(self, name, mapset='', *args, **kargs):

+ 8 - 9
lib/python/pygrass/raster/abstract.py

@@ -4,19 +4,12 @@ Created on Fri Aug 17 16:05:25 2012
 
 @author: pietro
 """
-
-
 import ctypes
 
-from numpy import isnan
-
 #
 # import GRASS modules
 #
-from grass.script import fatal, warning, gisenv
-from grass.script import core as grasscore
-#from grass.script import core
-#import grass.lib as grasslib
+from grass.script import fatal, gisenv
 import grass.lib.gis as libgis
 import grass.lib.raster as libraster
 
@@ -26,7 +19,7 @@ import grass.lib.raster as libraster
 from grass.pygrass import functions
 from grass.pygrass.gis.region import Region
 from grass.pygrass.errors import must_be_open
-from grass.pygrass.gis import Mapset
+
 #
 # import raster classes
 #
@@ -194,6 +187,12 @@ class RasterAbstractBase(object):
         if self.exist():
             self.info = Info(self.name, self.mapset)
 
+    def __enter__(self):
+        self.open('r')
+        return self
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        self.close()
 
     def _get_mtype(self):
         """Private method to get the Raster type"""