A community-maintained Python framework for creating mathematical animations.
Refactor config (#340)
Leo Torresc89a441d8b2f
diff --git a/manim/__init__.py b/manim/__init__.pyindex ea5e67915..b7170bccd 100644--- a/manim/__init__.py+++ b/manim/__init__.py@@ -1,12 +1,11 @@#!/usr/bin/env python-# Importing the config module should be the first thing we do, since other# modules depend on the global config dict for initialization. Note that the# global config dict is called 'config', just like the module itself. That's# why we import the module first with a different name, and then the dict.from . import config as _config-from .config import config+from .config import config, tempconfigfrom .constants import *diff --git a/manim/camera/camera.py b/manim/camera/camera.pyindex ee5cc6c3c..11834c921 100644--- a/manim/camera/camera.py+++ b/manim/camera/camera.py@@ -44,19 +44,13 @@ class Camera(object):CONFIG = {"background_image": None,- "pixel_height": config["pixel_height"],- "pixel_width": config["pixel_width"],- "frame_rate": config["frame_rate"],# Note: frame height and width will be resized to match# the pixel aspect ratio- "frame_height": config["frame_height"],- "frame_width": config["frame_width"],"frame_center": ORIGIN,"background_color": BLACK,"background_opacity": 1,# Points in vectorized mobjects with norm greater# than this value will be rescaled.- "max_allowable_norm": config["frame_width"],"image_mode": "RGBA","n_channels": 4,"pixel_array_dtype": "uint8",@@ -78,6 +72,26 @@ class Camera(object):Any local variables to be set."""digest_config(self, kwargs, locals())++ # All of the following are set to EITHER the value passed via kwargs,+ # OR the value stored in the global config dict at the time of+ # _instance construction_. Before, they were in the CONFIG dict, which+ # is a class attribute and is defined at the time of _class+ # definition_. This did not allow for creating two Cameras with+ # different configurations in the same session.+ for attr in [+ "pixel_height",+ "pixel_width",+ "frame_height",+ "frame_width",+ "frame_rate",+ ]:+ setattr(self, attr, kwargs.get(attr, config[attr]))++ # This one is in the same boat as the above, but it doesn't have the+ # same name as the corresponding key so it has to be handled on its own+ self.max_allowable_norm = config["frame_width"]+self.rgb_max_val = np.iinfo(self.pixel_array_dtype).maxself.pixel_array_to_cairo_context = {}diff --git a/manim/config.py b/manim/config.pyindex fa4a08af5..01f0adbc8 100644--- a/manim/config.py+++ b/manim/config.py@@ -6,6 +6,7 @@ config object."""import osimport sys+from contextlib import contextmanagerimport colour@@ -15,7 +16,55 @@ from .utils.config_utils import _run_config, _init_dirs, _from_command_linefrom .logger import loggerfrom .utils.tex import TexTemplate, TexTemplateFromFile-__all__ = ["file_writer_config", "config", "camera_config"]+__all__ = ["file_writer_config", "config", "camera_config", "tempconfig"]+++config = None+++@contextmanager+def tempconfig(temp):+ """Context manager that temporarily modifies the global config dict.++ The code block inside the ``with`` statement will use the modified config.+ After the code block, the config will be restored to its original value.++ Parameters+ ----------++ temp : :class:`dict`+ A dictionary whose keys will be used to temporarily update the global+ config.++ Examples+ --------+ Use ``with tempconfig({...})`` to temporarily change the default values of+ certain objects.++ .. code_block:: python++ c = Camera()+ c.frame_width == config['frame_width'] # -> True+ with tempconfig({'frame_width': 100}):+ c = Camera()+ c.frame_width == config['frame_width'] # -> False+ c.frame_width == 100 # -> True++ """+ global config+ original = config.copy()++ temp = {k: v for k, v in temp.items() if k in original}++ # In order to change the config that every module has acces to, use+ # update(), DO NOT use assignment. Assigning config = some_dict will just+ # make the local variable named config point to a new dictionary, it will+ # NOT change the dictionary that every module has a reference to.+ config.update(temp)+ try:+ yield+ finally:+ config.update(original) # update, not assignment!def _parse_config(config_parser, args):diff --git a/tests/test_camera.py b/tests/test_camera.pynew file mode 100644index 000000000..dd8f00f5b--- /dev/null+++ b/tests/test_camera.py@@ -0,0 +1,16 @@+import pytest+from manim import Camera, tempconfig, config+++def test_camera():+ """Test that Camera instances initialize to the correct config."""+ # by default, use the config+ assert Camera().frame_width == config["frame_width"]+ # init args override config+ assert Camera(frame_width=10).frame_width == 10++ # if config changes, reflect those changes+ with tempconfig({"frame_width": 100}):+ assert Camera().frame_width == 100+ # ..init args still override new config+ assert Camera(frame_width=10).frame_width == 10diff --git a/tests/test_config.py b/tests/test_config.pynew file mode 100644index 000000000..36c60243b--- /dev/null+++ b/tests/test_config.py@@ -0,0 +1,29 @@+import pytest+import numpy as np+from manim import config, tempconfig+++def test_tempconfig():+ """Test the tempconfig context manager."""+ original = config.copy()++ with tempconfig({"frame_width": 100, "frame_height": 42, "foo": -1}):+ # check that config was modified correctly+ assert config["frame_width"] == 100+ assert config["frame_height"] == 42++ # 'foo' is not a key in the original dict so it shouldn't be added+ assert "foo" not in config++ # check that no keys are missing and no new keys were added+ assert set(original.keys()) == set(config.keys())++ # check that the keys are still untouched+ assert set(original.keys()) == set(config.keys())++ # check that config is correctly restored+ for k, v in original.items():+ if isinstance(v, np.ndarray):+ assert np.allclose(config[k], v)+ else:+ assert config[k] == vdiff --git a/tests/test_logging/expected.txt b/tests/test_logging/expected.txtindex ccb8a2eae..f0920138e 100644--- a/tests/test_logging/expected.txt+++ b/tests/test_logging/expected.txt@@ -1,4 +1,4 @@-DEBUG Read configuration files: config.py:+DEBUG Read configuration files: config.py:DEBUG Animation : Partial movie file written in scene_file_writer.py:DEBUG Animation : Partial movie file written in scene_file_writer.py:DEBUG Animation : Partial movie file written in scene_file_writer.py: