Repository: kubernetes-client/python

Issue:
Document different patch types
This client supports multiple patch types (JSON patch, SMP, apply patch). See [source code](https://github.com/kubernetes-client/python/blob/02197998beba92de1a5c029e4e597fd901ec5aa8/kubernetes/client/rest.py#L159-L169). 

Our existing [example](https://github.com/kubernetes-client/python/blob/master/examples/patch_namespaced_config_map.py) isn't clear about what patch type is being used and what are the alternatives. 

We should have a document explains the different patch types, and have examples showing how to use them. Upstream Kubernetes also has related documents like [this one](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-api-machinery/strategic-merge-patch.md). 

This documentation could be helpful for issues like
- https://github.com/kubernetes-client/python/issues/2307
- https://github.com/kubernetes-client/python/issues/2305

The doc can be submitted to https://github.com/kubernetes-client/python/tree/master/devel and/or https://github.com/kubernetes-client/python/tree/master/doc

Hints from issue comments:
@h-ema-r: Hello sir, I would like to work on this issue and create documentation to explain the different patch types with examples.@userxpartha: hello mentor i would like to work on this issue so ,could you  please guide me to so that i can contribute .

@yliaog: /assign @h-ema-r @Varun270: @roycaihw Is this issue still open? I see a merged PR!!@yliaog: it's merged. closing this issue.

/close@k8s-ci-robot: @yliaog: Closing this issue.

<details>

In response to [this](https://github.com/kubernetes-client/python/issues/2326#issuecomment-2659798130):

>it's merged. closing this issue.
>
>/close


Instructions for interacting with me using PR comments are available [here](https://git.k8s.io/community/contributors/guide/pull-requests.md).  If you have questions or suggestions related to my behavior, please file an issue against the [kubernetes-sigs/prow](https://github.com/kubernetes-sigs/prow/issues/new?title=Prow%20issue:) repository.
</details>

Solution patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 74d60d176..97d8be5f7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,10 @@
+# v32.0.0
+
+Kubernetes API Version: v1.32.1
+
+### Bug or Regression
+- Fixed PortForward proxy to close local Python sockets when the WebSocket closes. (#2316, @anvilpete)
+
 # v32.0.0b1
 
 Kubernetes API Version: v1.32.1
diff --git a/README.md b/README.md
index 29812669f..7f148915e 100644
--- a/README.md
+++ b/README.md
@@ -101,7 +101,7 @@ supported versions of Kubernetes clusters.
 - [client 29.y.z](https://pypi.org/project/kubernetes/29.0.0/): Kubernetes 1.28 or below (+-), Kubernetes 1.29 (✓), Kubernetes 1.30 or above (+-)
 - [client 30.y.z](https://pypi.org/project/kubernetes/30.1.0/): Kubernetes 1.29 or below (+-), Kubernetes 1.30 (✓), Kubernetes 1.31 or above (+-)
 - [client 31.y.z](https://pypi.org/project/kubernetes/31.0.0/): Kubernetes 1.30 or below (+-), Kubernetes 1.31 (✓), Kubernetes 1.32 or above (+-)
-- [client 32.y.z](https://pypi.org/project/kubernetes/32.0.0b1/): Kubernetes 1.31 or below (+-), Kubernetes 1.32 (✓), Kubernetes 1.33 or above (+-)
+- [client 32.y.z](https://pypi.org/project/kubernetes/32.0.0/): Kubernetes 1.31 or below (+-), Kubernetes 1.32 (✓), Kubernetes 1.33 or above (+-)
 
 
 > See [here](#homogenizing-the-kubernetes-python-client-versions) for an explanation of why there is no v13-v16 release.
@@ -164,12 +164,13 @@ between client-python versions.
 | 28.0 Alpha/Beta | Kubernetes main repo, 1.28 branch    | ✗                             |
 | 28.0            | Kubernetes main repo, 1.28 branch    | ✗                             |
 | 29.0 Alpha/Beta | Kubernetes main repo, 1.29 branch    | ✗                             |
-| 29.0            | Kubernetes main repo, 1.29 branch    | ✓                             |
+| 29.0            | Kubernetes main repo, 1.29 branch    | ✗                             |
 | 30.0 Alpha/Beta | Kubernetes main repo, 1.30 branch    | ✗                             |
 | 30.0            | Kubernetes main repo, 1.30 branch    | ✓                             |
 | 31.0 Alpha/Beta | Kubernetes main repo, 1.31 branch    | ✗                             |
 | 31.0            | Kubernetes main repo, 1.31 branch    | ✓                             |
-| 32.0 Alpha/Beta | Kubernetes main repo, 1.32 branch    | ✓                             |
+| 32.0 Alpha/Beta | Kubernetes main repo, 1.32 branch    | ✗                             |
+| 32.0            | Kubernetes main repo, 1.32 branch    | ✓                             |
 
 > See [here](#homogenizing-the-kubernetes-python-client-versions) for an explanation of why there is no v13-v16 release.
 
diff --git a/devel/patch_types.md b/devel/patch_types.md
new file mode 100644
index 000000000..ac1395934
--- /dev/null
+++ b/devel/patch_types.md
@@ -0,0 +1,315 @@
+# Introduction to Kubernetes Patch Types
+In Kubernetes, patches are a way to make updates or changes to resources (like Pods, ConfigMaps, Deployments, etc.) without having to replace the entire resource. Patches allow you to modify specific parts of a resource while leaving the rest unchanged.
+
+## Types of Kubernetes Patches
+
+There are several types of patches that Kubernetes supports:
+
+1. JSON Merge Patch (Standard JSON Patch)
+2. Strategic Merge Patch
+3. JSON Patch
+4. Apply Patch (Server-Side Apply)
+
+## 1. JSON Merge Patch
+- JSON Merge Patch is based on the concept of merging JSON objects. When you apply a patch, you only need to specify the changes you want to make. Kubernetes will take your partial update and merge it with the existing resource.
+
+- This patch type is simple and works well when you need to update fields, such as changing a value or adding a new key.
+
+
+### Example Scenario:
+Imagine you have a Kubernetes Pod resource that looks like this:
+
+```
+apiVersion: v1
+kind: Pod
+metadata:
+  name: mypod
+spec:
+  containers:
+    - name: nginx
+      image: nginx:1.14
+    - name: redis
+      image: redis:5
+```
+Now, you want to change the image of the nginx container from nginx:1.14 to nginx:1.16. Instead of sending the entire resource, you can send only the part you want to change, like this:
+```
+{
+  "spec": {
+    "containers": [
+      {
+        "name": "nginx",
+        "image": "nginx:1.16"
+      }
+    ]
+  }
+}
+```
+
+When you send this patch to Kubernetes:
+
+It will replace the image of the nginx container with the new one (nginx:1.16).
+It will leave the redis container unchanged, because it's not included in the patch.
+
+### Example Code (Python):
+```
+from kubernetes import client, config
+
+def main():
+    config.load_kube_config()
+    v1 = client.CoreV1Api()
+
+    namespace = "default"
+    name = "mypod"
+
+    patch = {
+        "spec": {
+            "containers": [
+                {
+                    "name": "nginx",
+                    "image": "nginx:1.16"
+                }
+            ]
+        }
+    }
+
+    v1.patch_namespaced_pod(name=name, namespace=namespace, body=patch, content_type="application/merge-patch+json")
+
+if __name__ == "__main__":
+    main()
+
+```
+
+### After the  JSON Merge patch
+
+```
+apiVersion: v1
+kind: Pod
+metadata:
+  name: mypod
+spec:
+  containers:
+    - name: nginx
+      image: nginx:1.16  # Updated image version
+    - name: redis
+      image: redis:5  # Unchanged
+```
+
+
+## 2. Strategic Merge Patch
+Strategic Merge Patch is another type of patching mechanism, mostly used in Kubernetes, that allows updates to objects in a way that is more aware of the structure and semantics of the resource being modified. It is strategic because it understands the structure of the object, rather than blindly replacing it, and applies the changes in a smart way.
+- The patch itself is typically a JSON or YAML object, which contains the fields to be updated
+-	**Adds New Fields:** You can use it to add new fields or modify existing ones without affecting the rest of the object.
+- **Handle Lists or Arrays:** When dealing with lists (e.g., arrays or dictionaries), Strategic Merge Patch handles merging and updates intelligently.
+
+### Example of Strategic Merge Patch:
+let's suppose we have a yaml file Target Resource (Kubernetes ConfigMap):
+
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: my-configmap
+data:
+  key1: value1
+  key2: value2
+  list1:
+    - item1
+    - item2
+
+```
+
+Strategic Merge Patch
+```
+data:
+  key1: updated_value1  # Update key1
+  key3: value3          # Add new key3
+  list1:
+    - item1
+    - item2
+    - item3             # Add item3 to list1
+
+```
+
+Result after Strategic Merge Patch
+
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: my-configmap
+data:
+  key1: updated_value1  # key1 is updated
+  key2: value2          # key2 is unchanged
+  key3: value3          # key3 is added
+  list1:
+    - item1
+    - item2
+    - item3             # item3 is added to list1
+
+
+```
+
+
+## 3. JSON Patch
+- JSON Patch is a standard format that specifies a way to apply updates to a JSON document. Instead of sending a new or merged version of the object, JSON Patch describes how to modify the object step-by-step.
+- Operation-Based: A JSON Patch is an array of operations that describe modifications to a target JSON object.
+- Ideal when you need to perform multiple, specific operations on resource fields (e.g., replacing a value, adding new fields, or deleting specific values).
+
+### Patch Structure:
+A JSON Patch is an array of operations. Each operation is an object with:
+•	op: The operation type (e.g., add, remove, replace, etc.).
+•	path: A JSON Pointer string (defined in RFC 6901) that specifies the location in the document to apply the operation.
+•	value: (Optional) The new value to apply (used with operations like add, replace, or test).
+•	from: (Optional) Used in operations like move and copy to specify the source path.
+
+### Supported Operations for JSON Patch
+
+#### 1. **add**
+- Adds a value to a specified path.
+- If the path already exists, it adds the value to a list or object.
+
+Example:
+```json
+{ "op": "add", "path": "/a/b/c", "value": "foo" }
+```
+
+#### 2. **remove**
+- Removes the value at the specified path.
+
+Example:
+```json
+{ "op": "remove", "path": "/a/b/c" }
+```
+
+#### 3. **replace**
+- Replaces the value at the specified path.
+- Functionally similar to remove followed by add.
+
+Example:
+```json
+{ "op": "replace", "path": "/a/b/c", "value": "bar" }
+```
+
+#### 4. **move**
+- Moves a value from one path to another.
+
+Example:
+```json
+{ "op": "move", "from": "/a/b/c", "path": "/x/y/z" }
+```
+
+#### 5. **copy**
+- Copies a value from one path to another.
+
+Example:
+```json
+{ "op": "copy", "from": "/a/b/c", "path": "/x/y/z" }
+```
+
+#### 6. **test**
+- Tests whether a value at a specified path matches a given value.
+- Used for validation in transactional updates.
+
+Example:
+```json
+{ "op": "test", "path": "/a/b/c", "value": "foo" }
+```
+
+---
+
+#### Example: Applying a JSON Patch
+
+##### Target JSON Document:
+```json
+{
+  "a": {
+    "b": {
+      "c": "foo"
+    }
+  },
+  "x": {
+    "y": "bar"
+  }
+}
+```
+
+##### JSON Patch:
+```json
+[
+  { "op": "replace", "path": "/a/b/c", "value": "baz" },
+  { "op": "add", "path": "/a/d", "value": ["new", "value"] },
+  { "op": "remove", "path": "/x/y" }
+]
+```
+
+##### Result:
+```json
+{
+  "a": {
+    "b": {
+      "c": "baz"
+    },
+    "d": ["new", "value"]
+  },
+  "x": {}
+}
+```
+
+
+## 4. Apply Patch (Server-Side Apply)
+Server-Side Apply is a feature in Kubernetes that allows you to declaratively update resources by specifying their desired state. It provides an intuitive and robust way to manage resources without having to manually modify every field. It tracks which fields belong to which manager, which helps prevent conflicts when multiple clients (such as different controllers or users) update the same resource.
+
+Key Features:
+- Declarative Management: You provide the desired final state, and Kubernetes ensures the actual state matches it.
+- Conflict Detection: Ensures changes from different clients don’t conflict with each other.
+- Field Ownership: Kubernetes tracks which client or manager owns which fields of a resource.
+
+##### Example Scenario:
+
+You have a ConfigMap and want to update certain keys but leave others unchanged.
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: example-config
+  namespace: default
+data:
+  key1: value1
+  key2: value2
+```
+**Goal:**
+- You want to update key2 to new_value2 and 
+- add a new key key3 with a value value3. 
+- leave key1 unchanged
+
+##### Apply Patch YAML(Desired State):
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: example-config
+  namespace: default
+data:
+  key2: new_value2   # Update existing key
+  key3: value3       # Add new key
+
+```
+
+##### Resulting ConfigMap (after apply):
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: example-config
+  namespace: default
+data:
+  key1: value1          # Remains unchanged
+  key2: new_value2      # Updated value
+  key3: value3          # New key added
+
+```
+
+
+
+
+
diff --git a/doc/patch_types.md b/doc/patch_types.md
new file mode 100644
index 000000000..ac1395934
--- /dev/null
+++ b/doc/patch_types.md
@@ -0,0 +1,315 @@
+# Introduction to Kubernetes Patch Types
+In Kubernetes, patches are a way to make updates or changes to resources (like Pods, ConfigMaps, Deployments, etc.) without having to replace the entire resource. Patches allow you to modify specific parts of a resource while leaving the rest unchanged.
+
+## Types of Kubernetes Patches
+
+There are several types of patches that Kubernetes supports:
+
+1. JSON Merge Patch (Standard JSON Patch)
+2. Strategic Merge Patch
+3. JSON Patch
+4. Apply Patch (Server-Side Apply)
+
+## 1. JSON Merge Patch
+- JSON Merge Patch is based on the concept of merging JSON objects. When you apply a patch, you only need to specify the changes you want to make. Kubernetes will take your partial update and merge it with the existing resource.
+
+- This patch type is simple and works well when you need to update fields, such as changing a value or adding a new key.
+
+
+### Example Scenario:
+Imagine you have a Kubernetes Pod resource that looks like this:
+
+```
+apiVersion: v1
+kind: Pod
+metadata:
+  name: mypod
+spec:
+  containers:
+    - name: nginx
+      image: nginx:1.14
+    - name: redis
+      image: redis:5
+```
+Now, you want to change the image of the nginx container from nginx:1.14 to nginx:1.16. Instead of sending the entire resource, you can send only the part you want to change, like this:
+```
+{
+  "spec": {
+    "containers": [
+      {
+        "name": "nginx",
+        "image": "nginx:1.16"
+      }
+    ]
+  }
+}
+```
+
+When you send this patch to Kubernetes:
+
+It will replace the image of the nginx container with the new one (nginx:1.16).
+It will leave the redis container unchanged, because it's not included in the patch.
+
+### Example Code (Python):
+```
+from kubernetes import client, config
+
+def main():
+    config.load_kube_config()
+    v1 = client.CoreV1Api()
+
+    namespace = "default"
+    name = "mypod"
+
+    patch = {
+        "spec": {
+            "containers": [
+                {
+                    "name": "nginx",
+                    "image": "nginx:1.16"
+                }
+            ]
+        }
+    }
+
+    v1.patch_namespaced_pod(name=name, namespace=namespace, body=patch, content_type="application/merge-patch+json")
+
+if __name__ == "__main__":
+    main()
+
+```
+
+### After the  JSON Merge patch
+
+```
+apiVersion: v1
+kind: Pod
+metadata:
+  name: mypod
+spec:
+  containers:
+    - name: nginx
+      image: nginx:1.16  # Updated image version
+    - name: redis
+      image: redis:5  # Unchanged
+```
+
+
+## 2. Strategic Merge Patch
+Strategic Merge Patch is another type of patching mechanism, mostly used in Kubernetes, that allows updates to objects in a way that is more aware of the structure and semantics of the resource being modified. It is strategic because it understands the structure of the object, rather than blindly replacing it, and applies the changes in a smart way.
+- The patch itself is typically a JSON or YAML object, which contains the fields to be updated
+-	**Adds New Fields:** You can use it to add new fields or modify existing ones without affecting the rest of the object.
+- **Handle Lists or Arrays:** When dealing with lists (e.g., arrays or dictionaries), Strategic Merge Patch handles merging and updates intelligently.
+
+### Example of Strategic Merge Patch:
+let's suppose we have a yaml file Target Resource (Kubernetes ConfigMap):
+
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: my-configmap
+data:
+  key1: value1
+  key2: value2
+  list1:
+    - item1
+    - item2
+
+```
+
+Strategic Merge Patch
+```
+data:
+  key1: updated_value1  # Update key1
+  key3: value3          # Add new key3
+  list1:
+    - item1
+    - item2
+    - item3             # Add item3 to list1
+
+```
+
+Result after Strategic Merge Patch
+
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: my-configmap
+data:
+  key1: updated_value1  # key1 is updated
+  key2: value2          # key2 is unchanged
+  key3: value3          # key3 is added
+  list1:
+    - item1
+    - item2
+    - item3             # item3 is added to list1
+
+
+```
+
+
+## 3. JSON Patch
+- JSON Patch is a standard format that specifies a way to apply updates to a JSON document. Instead of sending a new or merged version of the object, JSON Patch describes how to modify the object step-by-step.
+- Operation-Based: A JSON Patch is an array of operations that describe modifications to a target JSON object.
+- Ideal when you need to perform multiple, specific operations on resource fields (e.g., replacing a value, adding new fields, or deleting specific values).
+
+### Patch Structure:
+A JSON Patch is an array of operations. Each operation is an object with:
+•	op: The operation type (e.g., add, remove, replace, etc.).
+•	path: A JSON Pointer string (defined in RFC 6901) that specifies the location in the document to apply the operation.
+•	value: (Optional) The new value to apply (used with operations like add, replace, or test).
+•	from: (Optional) Used in operations like move and copy to specify the source path.
+
+### Supported Operations for JSON Patch
+
+#### 1. **add**
+- Adds a value to a specified path.
+- If the path already exists, it adds the value to a list or object.
+
+Example:
+```json
+{ "op": "add", "path": "/a/b/c", "value": "foo" }
+```
+
+#### 2. **remove**
+- Removes the value at the specified path.
+
+Example:
+```json
+{ "op": "remove", "path": "/a/b/c" }
+```
+
+#### 3. **replace**
+- Replaces the value at the specified path.
+- Functionally similar to remove followed by add.
+
+Example:
+```json
+{ "op": "replace", "path": "/a/b/c", "value": "bar" }
+```
+
+#### 4. **move**
+- Moves a value from one path to another.
+
+Example:
+```json
+{ "op": "move", "from": "/a/b/c", "path": "/x/y/z" }
+```
+
+#### 5. **copy**
+- Copies a value from one path to another.
+
+Example:
+```json
+{ "op": "copy", "from": "/a/b/c", "path": "/x/y/z" }
+```
+
+#### 6. **test**
+- Tests whether a value at a specified path matches a given value.
+- Used for validation in transactional updates.
+
+Example:
+```json
+{ "op": "test", "path": "/a/b/c", "value": "foo" }
+```
+
+---
+
+#### Example: Applying a JSON Patch
+
+##### Target JSON Document:
+```json
+{
+  "a": {
+    "b": {
+      "c": "foo"
+    }
+  },
+  "x": {
+    "y": "bar"
+  }
+}
+```
+
+##### JSON Patch:
+```json
+[
+  { "op": "replace", "path": "/a/b/c", "value": "baz" },
+  { "op": "add", "path": "/a/d", "value": ["new", "value"] },
+  { "op": "remove", "path": "/x/y" }
+]
+```
+
+##### Result:
+```json
+{
+  "a": {
+    "b": {
+      "c": "baz"
+    },
+    "d": ["new", "value"]
+  },
+  "x": {}
+}
+```
+
+
+## 4. Apply Patch (Server-Side Apply)
+Server-Side Apply is a feature in Kubernetes that allows you to declaratively update resources by specifying their desired state. It provides an intuitive and robust way to manage resources without having to manually modify every field. It tracks which fields belong to which manager, which helps prevent conflicts when multiple clients (such as different controllers or users) update the same resource.
+
+Key Features:
+- Declarative Management: You provide the desired final state, and Kubernetes ensures the actual state matches it.
+- Conflict Detection: Ensures changes from different clients don’t conflict with each other.
+- Field Ownership: Kubernetes tracks which client or manager owns which fields of a resource.
+
+##### Example Scenario:
+
+You have a ConfigMap and want to update certain keys but leave others unchanged.
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: example-config
+  namespace: default
+data:
+  key1: value1
+  key2: value2
+```
+**Goal:**
+- You want to update key2 to new_value2 and 
+- add a new key key3 with a value value3. 
+- leave key1 unchanged
+
+##### Apply Patch YAML(Desired State):
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: example-config
+  namespace: default
+data:
+  key2: new_value2   # Update existing key
+  key3: value3       # Add new key
+
+```
+
+##### Resulting ConfigMap (after apply):
+```
+apiVersion: v1
+kind: ConfigMap
+metadata:
+  name: example-config
+  namespace: default
+data:
+  key1: value1          # Remains unchanged
+  key2: new_value2      # Updated value
+  key3: value3          # New key added
+
+```
+
+
+
+
+
diff --git a/kubernetes/base/config/exec_provider.py b/kubernetes/base/config/exec_provider.py
index 317a56695..c11c2a5f4 100644
--- a/kubernetes/base/config/exec_provider.py
+++ b/kubernetes/base/config/exec_provider.py
@@ -58,6 +58,15 @@ class ExecProvider(object):
         else:
             self.cluster = None
         self.cwd = cwd or None
+    
+    @property
+    def shell(self):
+        # for windows systems `shell` should be `True`
+        # for other systems like linux or darwin `shell` should be `False`
+        # referenes:
+        # https://github.com/kubernetes-client/python/pull/2289
+        # https://docs.python.org/3/library/sys.html#sys.platform
+        return sys.platform in ("win32", "cygwin")
 
     def run(self, previous_response=None):
         is_interactive = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
@@ -82,7 +91,7 @@ class ExecProvider(object):
             cwd=self.cwd,
             env=self.env,
             universal_newlines=True,
-            shell=True)
+            shell=self.shell)
         (stdout, stderr) = process.communicate()
         exit_code = process.wait()
         if exit_code != 0:
diff --git a/kubernetes/utils/quantity.py b/kubernetes/utils/quantity.py
index 68e57d980..484f34719 100644
--- a/kubernetes/utils/quantity.py
+++ b/kubernetes/utils/quantity.py
@@ -13,6 +13,19 @@
 # limitations under the License.
 from decimal import Decimal, InvalidOperation
 
+_EXPONENTS = {
+    "n": -3,
+    "u": -2,
+    "m": -1,
+    "K": 1,
+    "k": 1,
+    "M": 2,
+    "G": 3,
+    "T": 4,
+    "P": 5,
+    "E": 6,
+}
+
 
 def parse_quantity(quantity):
     """
@@ -35,17 +48,14 @@ def parse_quantity(quantity):
     if isinstance(quantity, (int, float, Decimal)):
         return Decimal(quantity)
 
-    exponents = {"n": -3, "u": -2, "m": -1, "K": 1, "k": 1, "M": 2,
-                 "G": 3, "T": 4, "P": 5, "E": 6}
-
     quantity = str(quantity)
     number = quantity
     suffix = None
     if len(quantity) >= 2 and quantity[-1] == "i":
-        if quantity[-2] in exponents:
+        if quantity[-2] in _EXPONENTS:
             number = quantity[:-2]
             suffix = quantity[-2:]
-    elif len(quantity) >= 1 and quantity[-1] in exponents:
+    elif len(quantity) >= 1 and quantity[-1] in _EXPONENTS:
         number = quantity[:-1]
         suffix = quantity[-1:]
 
@@ -68,8 +78,65 @@ def parse_quantity(quantity):
     if suffix == "ki":
         raise ValueError("{} has unknown suffix".format(quantity))
 
-    if suffix[0] not in exponents:
+    if suffix[0] not in _EXPONENTS:
         raise ValueError("{} has unknown suffix".format(quantity))
 
-    exponent = Decimal(exponents[suffix[0]])
+    exponent = Decimal(_EXPONENTS[suffix[0]])
     return number * (base ** exponent)
+
+
+def format_quantity(quantity_value, suffix, quantize=None) -> str:
+    """
+    Takes a decimal and produces a string value in kubernetes' canonical quantity form,
+    like "200Mi".Users can specify an additional decimal number to quantize the output.
+
+    Example -  Relatively increase pod memory limits:
+
+    # retrieve my_pod
+    current_memory: Decimal = parse_quantity(my_pod.spec.containers[0].resources.limits.memory)
+    desired_memory = current_memory * 1.2
+    desired_memory_str = format_quantity(desired_memory, suffix="Gi", quantize=Decimal(1))
+    # patch pod with desired_memory_str
+
+    'quantize=Decimal(1)' ensures that the result does not contain any fractional digits.
+
+    Supported SI suffixes:
+    base1024: Ki | Mi | Gi | Ti | Pi | Ei
+    base1000: n | u | m | "" | k | M | G | T | P | E
+
+    See https://github.com/kubernetes/apimachinery/blob/master/pkg/api/resource/quantity.go
+
+    Input:
+    quantity: Decimal.  Quantity as a number which is supposed to converted to a string
+                        with SI suffix.
+    suffix: string.     The desired suffix/unit-of-measure of the output string
+    quantize: Decimal.  Can be used to round/quantize the value before the string
+                        is returned. Defaults to None.
+
+    Returns:
+    string. Canonical Kubernetes quantity string containing the SI suffix.
+
+    Raises:
+    ValueError if the SI suffix is not supported.
+    """
+
+    if not suffix:
+        return str(quantity_value)
+
+    if suffix.endswith("i"):
+        base = 1024
+    elif len(suffix) == 1:
+        base = 1000
+    else:
+        raise ValueError(f"{quantity_value} has unknown suffix")
+
+    if suffix == "ki":
+        raise ValueError(f"{quantity_value} has unknown suffix")
+
+    if suffix[0] not in _EXPONENTS:
+        raise ValueError(f"{quantity_value} has unknown suffix")
+
+    different_scale = quantity_value / Decimal(base ** _EXPONENTS[suffix[0]])
+    if quantize:
+        different_scale = different_scale.quantize(quantize)
+    return str(different_scale) + suffix


Test patch:
diff --git a/kubernetes/e2e_test/test_utils.py b/kubernetes/e2e_test/test_utils.py
index 6579423c8..646081b8c 100644
--- a/kubernetes/e2e_test/test_utils.py
+++ b/kubernetes/e2e_test/test_utils.py
@@ -13,13 +13,15 @@
 # under the License.
 
 import unittest
+from decimal import Decimal
 from os import path
 
 import yaml
 
-from kubernetes import utils, client
+from kubernetes import client, utils
 from kubernetes.client.rest import ApiException
 from kubernetes.e2e_test import base
+from kubernetes.utils import quantity
 
 
 class TestUtils(unittest.TestCase):
@@ -605,3 +607,113 @@ class TestUtils(unittest.TestCase):
             name="mock-pod-1", namespace=self.test_namespace, body={})
         app_api.delete_namespaced_deployment(
             name="mock", namespace=self.test_namespace, body={})
+
+
+class TestUtilsUnitTests(unittest.TestCase):
+
+    def test_parse_quantity(self):
+        # == trivial returns ==
+        self.assertEqual(quantity.parse_quantity(Decimal(1)), Decimal(1))
+        self.assertEqual(quantity.parse_quantity(float(1)), Decimal(1))
+        self.assertEqual(quantity.parse_quantity(1), Decimal(1))
+
+        # == exceptions ==
+        self.assertRaises(
+            ValueError, lambda: quantity.parse_quantity("1000kb")
+        )
+        self.assertRaises(
+            ValueError, lambda: quantity.parse_quantity("1000ki")
+        )
+        self.assertRaises(ValueError, lambda: quantity.parse_quantity("1000foo"))
+        self.assertRaises(ValueError, lambda: quantity.parse_quantity("foo"))
+
+        # == no suffix ==
+        self.assertEqual(quantity.parse_quantity("1000"), Decimal(1000))
+
+        # == base 1024 ==
+        self.assertEqual(quantity.parse_quantity("1Ki"), Decimal(1024))
+        self.assertEqual(quantity.parse_quantity("1Mi"), Decimal(1024**2))
+        self.assertEqual(quantity.parse_quantity("1Gi"), Decimal(1024**3))
+        self.assertEqual(quantity.parse_quantity("1Ti"), Decimal(1024**4))
+        self.assertEqual(quantity.parse_quantity("1Pi"), Decimal(1024**5))
+        self.assertEqual(quantity.parse_quantity("1Ei"), Decimal(1024**6))
+        self.assertEqual(quantity.parse_quantity("1024Ki"), Decimal(1024**2))
+        self.assertEqual(quantity.parse_quantity("0.5Ki"), Decimal(512))
+
+        # == base 1000 ==
+        self.assertAlmostEqual(quantity.parse_quantity("1n"), Decimal(0.000_000_001))
+        self.assertAlmostEqual(quantity.parse_quantity("1u"), Decimal(0.000_001))
+        self.assertAlmostEqual(quantity.parse_quantity("1m"), Decimal(0.001))
+        self.assertEqual(quantity.parse_quantity("1k"), Decimal(1_000))
+        self.assertEqual(quantity.parse_quantity("1M"), Decimal(1_000_000))
+        self.assertEqual(quantity.parse_quantity("1G"), Decimal(1_000_000_000))
+        self.assertEqual(quantity.parse_quantity("1T"), Decimal(1_000_000_000_000))
+        self.assertEqual(quantity.parse_quantity("1P"), Decimal(1_000_000_000_000_000))
+        self.assertEqual(
+            quantity.parse_quantity("1E"), Decimal(1_000_000_000_000_000_000))
+        self.assertEqual(quantity.parse_quantity("1000k"), Decimal(1_000_000))
+        self.assertEqual(quantity.parse_quantity("500k"), Decimal(500_000))
+
+    def test_format_quantity(self):
+        """Unit test for quantity.format_quantity. Testing the different SI suffixes and
+        function should return the expected string"""
+
+        # == unknown suffixes ==
+        self.assertRaises(
+            ValueError, lambda: quantity.format_quantity(Decimal(1_000), "kb")
+        )
+        self.assertRaises(
+            ValueError, lambda: quantity.format_quantity(Decimal(1_000), "ki")
+        )
+        self.assertRaises(
+            ValueError, lambda: quantity.format_quantity(Decimal(1_000), "foo")
+        )
+
+        # == no suffix ==
+        self.assertEqual(quantity.format_quantity(Decimal(1_000), ""), "1000")
+        self.assertEqual(quantity.format_quantity(Decimal(1_000), None), "1000")
+
+        # == base 1024 ==
+        self.assertEqual(quantity.format_quantity(Decimal(1024), "Ki"), "1Ki")
+        self.assertEqual(quantity.format_quantity(Decimal(1024**2), "Mi"), "1Mi")
+        self.assertEqual(quantity.format_quantity(Decimal(1024**3), "Gi"), "1Gi")
+        self.assertEqual(quantity.format_quantity(Decimal(1024**4), "Ti"), "1Ti")
+        self.assertEqual(quantity.format_quantity(Decimal(1024**5), "Pi"), "1Pi")
+        self.assertEqual(quantity.format_quantity(Decimal(1024**6), "Ei"), "1Ei")
+        self.assertEqual(quantity.format_quantity(Decimal(1024**2), "Ki"), "1024Ki")
+        self.assertEqual(quantity.format_quantity(Decimal((1024**3) / 2), "Gi"), "0.5Gi")
+        # Decimal((1024**3)/3) are 0.3333333333333333148296162562Gi; expecting to
+        # be quantized to 0.3Gi
+        self.assertEqual(
+            quantity.format_quantity(
+                Decimal(
+                    (1024**3) / 3),
+                "Gi",
+                quantize=Decimal(.5)),
+            "0.3Gi")
+
+        # == base 1000 ==
+        self.assertEqual(quantity.format_quantity(Decimal(0.000_000_001), "n"), "1n")
+        self.assertEqual(quantity.format_quantity(Decimal(0.000_001), "u"), "1u")
+        self.assertEqual(quantity.format_quantity(Decimal(0.001), "m"), "1m")
+        self.assertEqual(quantity.format_quantity(Decimal(1_000), "k"), "1k")
+        self.assertEqual(quantity.format_quantity(Decimal(1_000_000), "M"), "1M")
+        self.assertEqual(quantity.format_quantity(Decimal(1_000_000_000), "G"), "1G")
+        self.assertEqual(
+            quantity.format_quantity(Decimal(1_000_000_000_000), "T"), "1T"
+        )
+        self.assertEqual(
+            quantity.format_quantity(Decimal(1_000_000_000_000_000), "P"), "1P"
+        )
+        self.assertEqual(
+            quantity.format_quantity(Decimal(1_000_000_000_000_000_000), "E"), "1E"
+        )
+        self.assertEqual(quantity.format_quantity(Decimal(1_000_000), "k"), "1000k")
+        # Decimal(1_000_000/3) are 333.3333333333333139307796955k; expecting to
+        # be quantized to 333k
+        self.assertEqual(
+            quantity.format_quantity(
+                Decimal(1_000_000 / 3), "k", quantize=Decimal(1000)
+            ),
+            "333k",
+        )