{"id":101208,"date":"2026-07-01T18:44:06","date_gmt":"2026-07-01T18:44:06","guid":{"rendered":"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/"},"modified":"2026-07-01T18:44:06","modified_gmt":"2026-07-01T18:44:06","slug":"cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit","status":"publish","type":"post","link":"https:\/\/youzum.net\/fr\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/","title":{"rendered":"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit"},"content":{"rendered":"<p class=\"wp-block-paragraph\">In this tutorial, we explore<a href=\"https:\/\/github.com\/baidu\/CUP\"> <strong>CUP<\/strong><\/a>, Baidu\u2019s Common Useful Python library, as a practical utility toolkit for building stronger Python workflows. We begin by setting up the library in a Colab-friendly environment and then move through its major subsystems step by step, including logging, decorators, nested configuration, caching, ID generation, thread pools, interruptible threads, delayed execution, time utilities, Linux resource monitoring, file locking, networking helpers, object storage interfaces, type maps, and built-in testing assertions. As we progress, we do not just call functions at random; we observe how each module fits into real-world development tasks such as monitoring, automation, concurrency, configuration management, and reliability checks.<\/p>\n<h2 class=\"wp-block-heading\"><strong>CUP Setup and Logging<\/strong><\/h2>\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\">\n<div class=\"control-language\">\n<div class=\"dm-buttons\">\n<div class=\"dm-buttons-left\">\n<div class=\"dm-button-snippet red-button\"><\/div>\n<div class=\"dm-button-snippet orange-button\"><\/div>\n<div class=\"dm-button-snippet green-button\"><\/div>\n<\/div>\n<div class=\"dm-buttons-right\"><a><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\">Copied<\/span><span class=\"dm-error-message\">Use a different Browser<\/span><\/a><\/div>\n<\/div>\n<pre class=\"no-line-numbers\"><code class=\"no-wrap language-php\">import os\nimport sys\nimport time\nimport threading\nimport tempfile\nimport datetime\nimport subprocess\ndef banner(title):\n   line = \"=\" * 70\n   print(\"n\" + line + \"n\" + title + \"n\" + line)\ndef skip(exc):\n   \"\"\"Report a gracefully-skipped section without aborting the notebook.\"\"\"\n   print(\"   [skipped \u2014 {}: {}]\".format(type(exc).__name__, exc))\nbanner(\"0. SETUP  (install + cup.platforms + cup.version)\")\nsubprocess.run(\n   [sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"cup\", \"pytz\"],\n   check=False,\n)\nimport cup\nver = getattr(cup, \"__version__\", None)\nif ver is None:\n   try:\n       from cup import version as _v\n       ver = getattr(_v, \"VERSION\", None) or getattr(_v, \"__version__\", \"unknown\")\n   except Exception:\n       ver = \"unknown\"\nprint(\"CUP version :\", ver)\nprint(\"Python      :\", sys.version.split()[0])\ntry:\n   from cup import platforms\n   print(\"is_linux    :\", platforms.is_linux())\n   print(\"is_mac      :\", platforms.is_mac())\n   print(\"is_windows  :\", platforms.is_windows())\n   print(\"is_py3      :\", platforms.is_py3())\nexcept Exception as e:\n   skip(e)\nbanner(\"1. LOGGING  (cup.log)\")\nLOGFILE = os.path.join(tempfile.gettempdir(), \"cup_tutorial.log\")\ntry:\n   from cup import log\n   log.init_comlog(\n       \"cup_tutorial\",\n       log.INFO,\n       LOGFILE,\n       log.ROTATION,\n       10 * 1024 * 1024,\n       True,\n       False,\n   )\n   log.info(\"hello from cup.log \u2014 written to file AND stdout\")\n   log.warning(\"a warning line\")\n   log.info_if(2 &gt; 1, \"info_if(True)  -&gt; emitted\")\n   log.info_if(1 &gt; 2, \"info_if(False) -&gt; you will NOT see this\")\n   log.setloglevel(log.DEBUG)\n   log.debug(\"debug visible after setloglevel(DEBUG)\")\n   try:\n       with open(LOGFILE) as fh:\n           last = [ln for ln in fh.read().splitlines() if ln.strip()][-1]\n       parsed = log.parse(last)\n       print(\"parsed last log line -&gt;\")\n       for k in (\"loglevel\", \"date\", \"time\", \"pid\", \"srcline\", \"msg\"):\n           if isinstance(parsed, dict) and k in parsed:\n               print(\"   {:8}: {}\".format(k, parsed[k]))\n   except Exception as e:\n       skip(e)\nexcept Exception as e:\n   skip(e)\n<\/code><\/pre>\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\">We begin by setting up the CUP tutorial environment and installing the required packages directly from Python. We define helper functions that keep the notebook readable and allow failed sections to be skipped safely. We then explore CUP version details, platform checks, and structured logging to understand the library\u2019s foundation.<\/p>\n<h2 class=\"wp-block-heading\"><strong>Decorators and Nested Config<\/strong><\/h2>\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\">\n<div class=\"control-language\">\n<div class=\"dm-buttons\">\n<div class=\"dm-buttons-left\">\n<div class=\"dm-button-snippet red-button\"><\/div>\n<div class=\"dm-button-snippet orange-button\"><\/div>\n<div class=\"dm-button-snippet green-button\"><\/div>\n<\/div>\n<div class=\"dm-buttons-right\"><a><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\">Copied<\/span><span class=\"dm-error-message\">Use a different Browser<\/span><\/a><\/div>\n<\/div>\n<pre class=\"no-line-numbers\"><code class=\"no-wrap language-php\">banner(\"2. DECORATORS  (cup.decorators)\")\ntry:\n   from cup import decorators\n   @decorators.Singleton\n   class AppConfig(object):\n       def __init__(self):\n           self.created_at = time.time()\n   a, b = AppConfig(), AppConfig()\n   print(\"Singleton: a is b -&gt;\", a is b, \"(same created_at:\",\n         a.created_at == b.created_at, \")\")\n   @decorators.TraceUsedTime(\n       b_print_stdout=True,\n       enter_msg=\"event_id=0xABCDE enter\",\n       leave_msg=\"event_id=0xABCDE leave\",\n   )\n   def heavy_compute():\n       time.sleep(0.2)\n       return sum(range(200000))\n   print(\"heavy_compute() =\", heavy_compute())\n   @decorators.needlinux\n   def linux_only():\n       return \"this body is allowed to run on Linux\"\n   print(\"needlinux -&gt;\", linux_only())\nexcept Exception as e:\n   skip(e)\nbanner(\"3. RICH NESTED CONFIG  (cup.util.conf)\")\nCONF_PATH = os.path.join(tempfile.gettempdir(), \"cup_demo.conf\")\nCONF_TEXT = \"\"\"\n# ---- global scalars (layer 0) ----\nhost: abc.com\nport: 12345\ndebug: false\n[monitor]\nenabled: true\ninterval: 60\nregex: sshd\n[.thresholds]\ncpu_max: 90\nmem_max: 80\n[..actions]\non_breach: alert\n[storage]\n@path: \/data\/disk1\n@path: \/data\/disk2\n@path: \/data\/disk3\n\"\"\"\ntry:\n   from cup.util import conf\n   with open(CONF_PATH, \"w\") as fh:\n       fh.write(CONF_TEXT)\n   cfg = conf.Configure2Dict(CONF_PATH, separator=\":\").get_dict()\n   print(\"host                          :\", cfg[\"host\"])\n   print(\"port                          :\", cfg[\"port\"])\n   print(\"monitor.enabled               :\", cfg[\"monitor\"][\"enabled\"])\n   print(\"monitor.regex                 :\", cfg[\"monitor\"][\"regex\"])\n   print(\"monitor.thresholds.cpu_max    :\", cfg[\"monitor\"][\"thresholds\"][\"cpu_max\"])\n   print(\"monitor.thresholds.actions    :\",\n         cfg[\"monitor\"][\"thresholds\"][\"actions\"][\"on_breach\"])\n   print(\"storage.path (repeated @ -&gt; list):\", list(cfg[\"storage\"][\"path\"]))\n   cfg[\"port\"] = \"10085\"\n   cfg[\"monitor\"][\"thresholds\"][\"actions\"][\"on_breach\"] = \"restart\"\n   NEW_PATH = CONF_PATH + \".new\"\n   conf.Dict2Configure(cfg, separator=\":\").write_conf(NEW_PATH)\n   re_read = conf.Configure2Dict(NEW_PATH, separator=\":\").get_dict()\n   print(\"round-trip port               :\", re_read[\"port\"], \"(was 12345)\")\n   print(\"round-trip on_breach          :\",\n         re_read[\"monitor\"][\"thresholds\"][\"actions\"][\"on_breach\"], \"(was alert)\")\nexcept Exception as e:\n   skip(e)\n<\/code><\/pre>\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\">We move on to CUP decorators and see how they help us create single-instance classes, track execution time, and protect Linux-only functions. We then work with CUP\u2019s rich configuration system and load a nested configuration file with sections, child sections, and repeated values. We also update the configuration and write it back to disk to confirm that the read-modify-write flow works correctly.<\/p>\n<h2 class=\"wp-block-heading\"><strong>Caching, IDs, Thread Pools<\/strong><\/h2>\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\">\n<div class=\"control-language\">\n<div class=\"dm-buttons\">\n<div class=\"dm-buttons-left\">\n<div class=\"dm-button-snippet red-button\"><\/div>\n<div class=\"dm-button-snippet orange-button\"><\/div>\n<div class=\"dm-button-snippet green-button\"><\/div>\n<\/div>\n<div class=\"dm-buttons-right\"><a><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\">Copied<\/span><span class=\"dm-error-message\">Use a different Browser<\/span><\/a><\/div>\n<\/div>\n<pre class=\"no-line-numbers\"><code class=\"no-wrap language-php\">banner(\"4. IN-MEMORY KV CACHE  (cup.cache)\")\ntry:\n   from cup import cache\n   kv = cache.KVCache(name=\"demo\")\n   kv.set({\"user:1\": \"alice\", \"user:2\": \"bob\"}, expire_sec=2)\n   kv.set({\"config:flag\": \"on\"}, expire_sec=None)\n   print(\"size after sets         :\", kv.size())\n   print(\"get user:1              :\", kv.get(\"user:1\"))\n   print(\"get missing key         :\", kv.get(\"nope\"))\n   print(\"sleeping 2.2s to let the 2s-TTL keys expire ...\")\n   time.sleep(2.2)\n   print(\"get user:1 (expired)    :\", kv.get(\"user:1\"))\n   print(\"get config:flag (eternal):\", kv.get(\"config:flag\"))\n   reclaimed = kv.pop_n_expired(0)\n   print(\"pop_n_expired reclaimed :\", list(reclaimed.keys()) if reclaimed else [])\nexcept Exception as e:\n   skip(e)\nbanner(\"5. UNIQUE ID GENERATION  (cup.services.generator)\")\ntry:\n   from cup.services import generator\n   gman = generator.CGeneratorMan()\n   print(\"uniqname                :\", gman.get_uniqname())\n   print(\"next_uniq_num           :\", gman.get_next_uniq_num())\n   print(\"next_uniq_num (again)   :\", gman.get_next_uniq_num(), \"(monotonic)\")\n   if hasattr(gman, \"get_uuid\"):\n       try:\n           print(\"get_uuid                :\", gman.get_uuid())\n       except Exception as e:\n           skip(e)\n   if hasattr(gman, \"get_random_str\"):\n       try:\n           print(\"get_random_str(16)      :\", gman.get_random_str(16))\n       except Exception as e:\n           skip(e)\n   print(\"singleton check         :\", generator.CGeneratorMan() is gman)\n   try:\n       cyc = generator.CycleIDGenerator(\"127.0.0.1\", 8080)\n       i1, i2 = cyc.next_id(), cyc.next_id()\n       print(\"CycleIDGenerator id #1  :\", i1)\n       print(\"CycleIDGenerator id #2  :\", i2, \"(incremented)\")\n       print(\"id #1 as hex            :\", generator.CycleIDGenerator.id2_hexstring(i1))\n   except Exception as e:\n       skip(e)\nexcept Exception as e:\n   skip(e)\nbanner(\"6. THREAD POOL  (cup.services.threadpool)\")\ntry:\n   from cup.services import threadpool\n   pool = threadpool.ThreadPool(minthreads=2, maxthreads=4, name=\"demo-pool\")\n   pool.start()\n   results, rlock = [], threading.Lock()\n   def square(n):\n       time.sleep(0.03)\n       with rlock:\n           results.append(n * n)\n       return n * n\n   for i in range(8):\n       pool.add_1job(square, i)\n   callback_log = []\n   def on_done(ok, result):\n       callback_log.append((ok, result))\n   pool.add_1job_with_callback(on_done, square, 100)\n   def will_fail():\n       raise RuntimeError(\"boom inside worker\")\n   pool.add_1job_with_callback(on_done, will_fail)\n   time.sleep(0.5)\n   print(\"live stats              :\", pool.get_stats())\n   pool.stop()\n   print(\"squares collected       :\", sorted(results))\n   print(\"callback results        :\", callback_log)\nexcept Exception as e:\n   skip(e)\n<\/code><\/pre>\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\">We use CUP\u2019s in-memory cache to store key-value pairs with temporary and permanent lifetimes. We then generate unique names, counters, UUID-style values, random strings, and cycling IDs for distributed-style identifiers. We also create a thread pool, submit jobs, collect results, and observe callback behavior for both successful and failed tasks.<\/p>\n<h2 class=\"wp-block-heading\"><strong>Threads, Scheduling, Time Utilities<\/strong><\/h2>\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\">\n<div class=\"control-language\">\n<div class=\"dm-buttons\">\n<div class=\"dm-buttons-left\">\n<div class=\"dm-button-snippet red-button\"><\/div>\n<div class=\"dm-button-snippet orange-button\"><\/div>\n<div class=\"dm-button-snippet green-button\"><\/div>\n<\/div>\n<div class=\"dm-buttons-right\"><a><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\">Copied<\/span><span class=\"dm-error-message\">Use a different Browser<\/span><\/a><\/div>\n<\/div>\n<pre class=\"no-line-numbers\"><code class=\"no-wrap language-php\">banner(\"7. INTERRUPTIBLE THREADS + RW LOCK  (cup.thread)\")\ntry:\n   from cup import thread as cupthread\n   rw = cupthread.RWLock()\n   rw.acquire_readlock()\n   rw.acquire_readlock()\n   print(\"acquired 2 read locks concurrently\")\n   rw.release_readlock()\n   rw.release_readlock()\n   rw.acquire_writelock()\n   print(\"acquired exclusive write lock\")\n   rw.release_writelock()\n   stop_flag = {\"running\": True}\n   def busy_loop():\n       while stop_flag[\"running\"]:\n           time.sleep(0.05)\n   t = cupthread.CupThread(target=busy_loop)\n   t.daemon = True\n   t.start()\n   print(\"worker python tid       :\", t.get_my_tid())\n   stop_flag[\"running\"] = False\n   ok = t.terminate()\n   print(\"CupThread.terminate -&gt;  :\", ok)\nexcept Exception as e:\n   skip(e)\nbanner(\"8. DELAY \/ CRON EXECUTOR  (cup.services.executor)\")\ntry:\n   from cup.services import executor\n   URGENCY = getattr(executor, \"URGENCY_NORMAL\", 0)\n   svc = executor.ExecutionService(\n       delay_exe_thdnum=2, queue_exec_thdnum=2, name=\"exec-demo\"\n   )\n   svc.start()\n   fired = []\n   def task(tag):\n       fired.append((tag, round(time.time(), 3)))\n   svc.delay_exec(0.3, task, URGENCY, \"delayed-0.3s\")\n   svc.queue_exec(task, URGENCY, \"queued-now\")\n   time.sleep(0.8)\n   svc.stop()\n   print(\"fired (tag, ts)         :\", fired)\n   try:\n       import pytz\n       import hashlib\n       tz = pytz.timezone(\"Asia\/Shanghai\")\n       timer = {\"minute\": [0, 30], \"hour\": None,\n                \"weekday\": None, \"monthday\": None, \"month\": None}\n       task_uuid = hashlib.md5(b\"demo-cron\").hexdigest()\n       ctask = executor.CronTask(\"demo-cron\", tz, timer, task_uuid, task, \"cron-arg\")\n       print(\"cron next_schedtime     :\", ctask.next_schedtime())\n       print(\"cron 32-byte taskid     :\", ctask.taskid())\n   except Exception as e:\n       skip(e)\nexcept Exception as e:\n   skip(e)\nbanner(\"9. TIME HELPERS  (cup.timeplus)\")\ntry:\n   from cup import timeplus\n   import pytz\n   print(\"get_str_now (default)   :\", timeplus.get_str_now())\n   print(\"get_str_now (custom fmt):\", timeplus.get_str_now(\"%Y\/%m\/%d %H:%M:%S\"))\n   tp = timeplus.TimePlus(pytz.timezone(\"Asia\/Shanghai\"))\n   now_utc = datetime.datetime.utcnow()\n   print(\"naive utc now           :\", now_utc)\n   print(\"-&gt; Shanghai local       :\", tp.utc2local(now_utc))\nexcept Exception as e:\n   skip(e)\n<\/code><\/pre>\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\">We explore CUP\u2019s thread utilities by using a reader-writer lock and an interruptible thread. We then run delayed and queued tasks through the execution service to understand simple scheduling behavior. We also create a cron-style task and inspect its next scheduled run time without waiting for the real clock to tick.<\/p>\n<h2 class=\"wp-block-heading\"><strong>System Resources and Storage<\/strong><\/h2>\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\">\n<div class=\"control-language\">\n<div class=\"dm-buttons\">\n<div class=\"dm-buttons-left\">\n<div class=\"dm-button-snippet red-button\"><\/div>\n<div class=\"dm-button-snippet orange-button\"><\/div>\n<div class=\"dm-button-snippet green-button\"><\/div>\n<\/div>\n<div class=\"dm-buttons-right\"><a><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\">Copied<\/span><span class=\"dm-error-message\">Use a different Browser<\/span><\/a><\/div>\n<\/div>\n<pre class=\"no-line-numbers\"><code class=\"no-wrap language-php\">banner(\"10. SYSTEM RESOURCES  (cup.res.linux)\")\ntry:\n   from cup.res import linux as reslinux\n   try:\n       print(\"cpu cores               :\", reslinux.get_cpu_nums())\n   except Exception as e:\n       skip(e)\n   try:\n       cpu = reslinux.get_cpu_usage(intvl_in_sec=1)\n       print(\"cpu usage sample        :\", cpu, \"| usr=\", getattr(cpu, \"usr\", \"?\"))\n   except Exception as e:\n       skip(e)\n   try:\n       mem = reslinux.get_meminfo()\n       gb = 1024.0 ** 3\n       print(\"mem total \/ available   : {:.2f} GB \/ {:.2f} GB\".format(\n           mem.total \/ gb, mem.available \/ gb))\n   except Exception as e:\n       skip(e)\n   try:\n       print(\"kernel version          :\", reslinux.get_kernel_version())\n   except Exception as e:\n       skip(e)\n   try:\n       all_pids = reslinux.pids()\n       print(\"live process count      :\", len(all_pids))\n   except Exception as e:\n       skip(e)\n   try:\n       me = reslinux.Process(os.getpid())\n       name = me.get_process_name() if hasattr(me, \"get_process_name\") else \"?\"\n       status = me.get_process_status() if hasattr(me, \"get_process_status\") else \"?\"\n       print(\"this process name\/status:\", name, \"\/\", status)\n   except Exception as e:\n       skip(e)\nexcept Exception as e:\n   skip(e)\nbanner(\"11. FILE UTILITIES  (cup.exfile)\")\ntry:\n   from cup import exfile\n   lock_path = os.path.join(tempfile.gettempdir(), \"cup_demo.lock\")\n   flock = exfile.LockFile(lock_path)\n   got = flock.lock(blocking=True)\n   print(\"acquired file lock      :\", got)\n   print(\"lock file path          :\", flock.filepath())\n   flock.unlock()\n   print(\"released file lock      : True\")\nexcept Exception as e:\n   skip(e)\nbanner(\"12. NETWORKING HELPERS  (cup.net)\")\ntry:\n   from cup import net as cupnet\n   try:\n       print(\"local hostname          :\", cupnet.get_local_hostname())\n   except Exception as e:\n       skip(e)\n   try:\n       print(\"host ip                 :\", cupnet.get_hostip())\n   except Exception as e:\n       skip(e)\n   try:\n       print(\"local port 9999 free?   :\", cupnet.localport_free(9999))\n   except Exception as e:\n       skip(e)\nexcept Exception as e:\n   skip(e)\nbanner(\"13. UNIFIED OBJECT STORAGE  (cup.storage.obj)\")\ntry:\n   from cup.storage import obj as cupobj\n   print(\"available backends      :\",\n         [n for n in dir(cupobj) if n.endswith(\"ObjectSystem\")])\n   los = None\n   for ctor in (lambda: cupobj.LocalObjectSystem(tempfile.gettempdir()),\n                lambda: cupobj.LocalObjectSystem({}),\n                lambda: cupobj.LocalObjectSystem()):\n       try:\n           los = ctor()\n           break\n       except Exception:\n           continue\n   if los is None:\n       print(\"   LocalObjectSystem ctor varies by version \u2014 see docs for \"\n             \"your release's exact signature.\")\n   else:\n       print(\"LocalObjectSystem ready :\", type(los).__name__,\n             \"(put\/get\/head\/delete available)\")\nexcept Exception as e:\n   skip(e)\n<\/code><\/pre>\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\">We inspect Linux system resources, including CPU cores, CPU usage, memory, kernel version, process count, and current process status. We then use CUP\u2019s file utility module to acquire and release an advisory lock for safe single-instance execution. We also test networking helpers and probe the object storage interface to see which storage backends are available.<\/p>\n<h2 class=\"wp-block-heading\"><strong>Type Maps and Assertions<\/strong><\/h2>\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\">\n<div class=\"control-language\">\n<div class=\"dm-buttons\">\n<div class=\"dm-buttons-left\">\n<div class=\"dm-button-snippet red-button\"><\/div>\n<div class=\"dm-button-snippet orange-button\"><\/div>\n<div class=\"dm-button-snippet green-button\"><\/div>\n<\/div>\n<div class=\"dm-buttons-right\"><a><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\">Copied<\/span><span class=\"dm-error-message\">Use a different Browser<\/span><\/a><\/div>\n<\/div>\n<pre class=\"no-line-numbers\"><code class=\"no-wrap language-php\">banner(\"14. BIDIRECTIONAL TYPE MAPS  (cup.flag)\")\ntry:\n   from cup import flag\n   tman = flag.TypeMan()\n   tman.register_types({\"LOGIN\": 1, \"LOGOUT\": 2, \"HEARTBEAT\": 3, \"DATA\": 4})\n   print(\"LOGIN     -&gt; number     :\", tman.getnumber_bykey(\"LOGIN\"))\n   print(\"number 2  -&gt; key        :\", tman.getkey_bynumber(2))\n   print(\"all registered keys     :\", list(tman.get_key_list()))\nexcept Exception as e:\n   skip(e)\nbanner(\"15. BUILT-IN TEST ASSERTIONS  (cup.unittest)\")\ntry:\n   from cup import unittest as cup_unittest\n   cup_unittest.assert_eq(2 + 2, 4)\n   cup_unittest.assert_ne(1, 2)\n   cup_unittest.assert_true(isinstance([], list))\n   cup_unittest.assert_gt(5, 3)\n   cup_unittest.assert_eq_one(\"b\", [\"a\", \"b\", \"c\"])\n   def raises_value_error():\n       raise ValueError(\"expected\")\n   cup_unittest.expect_raise(raises_value_error, ValueError)\n   print(\"all passing assertions   : OK\")\n   try:\n       cup_unittest.assert_eq(1, 2, \"intentional failure demo\")\n   except Exception as e:\n       print(\"caught intended failure  :\", type(e).__name__)\nexcept Exception as e:\n   skip(e)\nbanner(\"DONE \u2014 you exercised 15 CUP subsystems\")\nprint(\"\"\"\nWhat you just used, by module:\n cup.log .................. structured, rotating, parseable logging\n cup.decorators ........... Singleton, TraceUsedTime, platform guards\n cup.util.conf ............ nested config with sections + @arrays (round-trip)\n cup.cache ................ TTL KV cache (get() extends lifetime)\n cup.services.generator ... host-unique names, counters, cycling 128-bit IDs\n cup.services.threadpool .. pool with result\/failure callbacks + live stats\n cup.thread ............... interruptible CupThread + reader\/writer RWLock\n cup.services.executor .... delay_exec \/ queue_exec + crontab-style CronTask\n cup.timeplus ............. now-formatting + safe tz&lt;-&gt;UTC conversion\n cup.res.linux ............ \/proc cpu, memory, kernel, process introspection\n cup.exfile ............... advisory single-instance file locking\n cup.net .................. hostname \/ ip \/ free-port helpers\n cup.storage.obj .......... one API over Local \/ FTP \/ S3 \/ AFS backends\n cup.flag ................. bidirectional key&lt;-&gt;number type tables\n cup.unittest ............. assertion toolkit that plays well with try\/except\nNext steps: API reference at https:\/\/cup.iobusy.com  \u2022  source at\nhttps:\/\/github.com\/baidu\/CUP (browse src\/cup\/ and the cup_test\/ suite).\n\"\"\")\n<\/code><\/pre>\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\">We use CUP\u2019s flag utilities to create bidirectional mappings between message names and numeric codes. We then run CUP\u2019s built-in assertion helpers to validate equality, inequality, truth checks, comparisons, membership, and expected exceptions. We finish the tutorial by summarizing every CUP subsystem we exercise and connecting each one to a practical development use case.<\/p>\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n<p class=\"wp-block-paragraph\">In conclusion, we completed a broad hands-on tour of CUP and understand how its utilities can support production-style Python applications. We saw how CUP helps us structure logs, manage runtime configuration, cache temporary data, generate unique identifiers, coordinate threads, inspect system resources, protect files with locks, and validate behavior through assertions. It sets us a compact but useful foundation for using CUP in scripts, backend services, automation jobs, and system-level Python projects where reliability, observability, and practical tooling matter.<\/p>\n<p class=\"wp-block-paragraph\">\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<\/p><p class=\"wp-block-paragraph\">Check out the<strong>\u00a0<a href=\"https:\/\/github.com\/MARKTECHPOST-AI-MEDIA-INC\/AI-Agents-Projects-Tutorials\/blob\/main\/Distributed%20Systems\/baidu_cup_practical_python_system_utilities_tutorial_Marktechpost.ipynb\" target=\"_blank\" rel=\"noreferrer noopener\">FULL CODES here<\/a><\/strong>.<strong>\u00a0<\/strong>Also,\u00a0feel free to follow us on\u00a0<strong><a href=\"https:\/\/x.com\/intent\/follow?screen_name=marktechpost\" target=\"_blank\" rel=\"noreferrer noopener\"><mark>Twitter<\/mark><\/a><\/strong>\u00a0and don\u2019t forget to join our\u00a0<strong><a href=\"https:\/\/www.reddit.com\/r\/machinelearningnews\/\" target=\"_blank\" rel=\"noreferrer noopener\">150k+ML SubReddit<\/a><\/strong>\u00a0and Subscribe to\u00a0<strong><a href=\"https:\/\/www.aidevsignals.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">our Newsletter<\/a><\/strong>. Wait! are you on telegram?\u00a0<strong><a href=\"https:\/\/t.me\/machinelearningresearchnews\" target=\"_blank\" rel=\"noreferrer noopener\">now you can join us on telegram as well.<\/a><\/strong><\/p>\n<p class=\"wp-block-paragraph\">Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.?\u00a0<strong><a href=\"https:\/\/forms.gle\/wbash1wF6efRj8G58\" target=\"_blank\" rel=\"noreferrer noopener\"><mark>Connect with us<\/mark><\/a><\/strong><\/p>\n<p>The post <a href=\"https:\/\/www.marktechpost.com\/2026\/06\/30\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/\">CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit<\/a> appeared first on <a href=\"https:\/\/www.marktechpost.com\/\">MarkTechPost<\/a>.<\/p>","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we explore CUP, Baidu\u2019s Common Useful Python library, as a practical utility toolkit for building stronger Python workflows. We begin by setting up the library in a Colab-friendly environment and then move through its major subsystems step by step, including logging, decorators, nested configuration, caching, ID generation, thread pools, interruptible threads, delayed execution, time utilities, Linux resource monitoring, file locking, networking helpers, object storage interfaces, type maps, and built-in testing assertions. As we progress, we do not just call functions at random; we observe how each module fits into real-world development tasks such as monitoring, automation, concurrency, configuration management, and reliability checks. CUP Setup and Logging Copy CodeCopiedUse a different Browser import os import sys import time import threading import tempfile import datetime import subprocess def banner(title): line = &#8220;=&#8221; * 70 print(&#8220;n&#8221; + line + &#8220;n&#8221; + title + &#8220;n&#8221; + line) def skip(exc): &#8220;&#8221;&#8221;Report a gracefully-skipped section without aborting the notebook.&#8221;&#8221;&#8221; print(&#8221; [skipped \u2014 {}: {}]&#8221;.format(type(exc).__name__, exc)) banner(&#8220;0. SETUP (install + cup.platforms + cup.version)&#8221;) subprocess.run( [sys.executable, &#8220;-m&#8221;, &#8220;pip&#8221;, &#8220;install&#8221;, &#8220;-q&#8221;, &#8220;cup&#8221;, &#8220;pytz&#8221;], check=False, ) import cup ver = getattr(cup, &#8220;__version__&#8221;, None) if ver is None: try: from cup import version as _v ver = getattr(_v, &#8220;VERSION&#8221;, None) or getattr(_v, &#8220;__version__&#8221;, &#8220;unknown&#8221;) except Exception: ver = &#8220;unknown&#8221; print(&#8220;CUP version :&#8221;, ver) print(&#8220;Python :&#8221;, sys.version.split()[0]) try: from cup import platforms print(&#8220;is_linux :&#8221;, platforms.is_linux()) print(&#8220;is_mac :&#8221;, platforms.is_mac()) print(&#8220;is_windows :&#8221;, platforms.is_windows()) print(&#8220;is_py3 :&#8221;, platforms.is_py3()) except Exception as e: skip(e) banner(&#8220;1. LOGGING (cup.log)&#8221;) LOGFILE = os.path.join(tempfile.gettempdir(), &#8220;cup_tutorial.log&#8221;) try: from cup import log log.init_comlog( &#8220;cup_tutorial&#8221;, log.INFO, LOGFILE, log.ROTATION, 10 * 1024 * 1024, True, False, ) log.info(&#8220;hello from cup.log \u2014 written to file AND stdout&#8221;) log.warning(&#8220;a warning line&#8221;) log.info_if(2 &gt; 1, &#8220;info_if(True) -&gt; emitted&#8221;) log.info_if(1 &gt; 2, &#8220;info_if(False) -&gt; you will NOT see this&#8221;) log.setloglevel(log.DEBUG) log.debug(&#8220;debug visible after setloglevel(DEBUG)&#8221;) try: with open(LOGFILE) as fh: last = [ln for ln in fh.read().splitlines() if ln.strip()][-1] parsed = log.parse(last) print(&#8220;parsed last log line -&gt;&#8221;) for k in (&#8220;loglevel&#8221;, &#8220;date&#8221;, &#8220;time&#8221;, &#8220;pid&#8221;, &#8220;srcline&#8221;, &#8220;msg&#8221;): if isinstance(parsed, dict) and k in parsed: print(&#8221; {:8}: {}&#8221;.format(k, parsed[k])) except Exception as e: skip(e) except Exception as e: skip(e) We begin by setting up the CUP tutorial environment and installing the required packages directly from Python. We define helper functions that keep the notebook readable and allow failed sections to be skipped safely. We then explore CUP version details, platform checks, and structured logging to understand the library\u2019s foundation. Decorators and Nested Config Copy CodeCopiedUse a different Browser banner(&#8220;2. DECORATORS (cup.decorators)&#8221;) try: from cup import decorators @decorators.Singleton class AppConfig(object): def __init__(self): self.created_at = time.time() a, b = AppConfig(), AppConfig() print(&#8220;Singleton: a is b -&gt;&#8221;, a is b, &#8220;(same created_at:&#8221;, a.created_at == b.created_at, &#8220;)&#8221;) @decorators.TraceUsedTime( b_print_stdout=True, enter_msg=&#8221;event_id=0xABCDE enter&#8221;, leave_msg=&#8221;event_id=0xABCDE leave&#8221;, ) def heavy_compute(): time.sleep(0.2) return sum(range(200000)) print(&#8220;heavy_compute() =&#8221;, heavy_compute()) @decorators.needlinux def linux_only(): return &#8220;this body is allowed to run on Linux&#8221; print(&#8220;needlinux -&gt;&#8221;, linux_only()) except Exception as e: skip(e) banner(&#8220;3. RICH NESTED CONFIG (cup.util.conf)&#8221;) CONF_PATH = os.path.join(tempfile.gettempdir(), &#8220;cup_demo.conf&#8221;) CONF_TEXT = &#8220;&#8221;&#8221; # &#8212;- global scalars (layer 0) &#8212;- host: abc.com port: 12345 debug: false [monitor] enabled: true interval: 60 regex: sshd [.thresholds] cpu_max: 90 mem_max: 80 [..actions] on_breach: alert [storage] @path: \/data\/disk1 @path: \/data\/disk2 @path: \/data\/disk3 &#8220;&#8221;&#8221; try: from cup.util import conf with open(CONF_PATH, &#8220;w&#8221;) as fh: fh.write(CONF_TEXT) cfg = conf.Configure2Dict(CONF_PATH, separator=&#8221;:&#8221;).get_dict() print(&#8220;host :&#8221;, cfg[&#8220;host&#8221;]) print(&#8220;port :&#8221;, cfg[&#8220;port&#8221;]) print(&#8220;monitor.enabled :&#8221;, cfg[&#8220;monitor&#8221;][&#8220;enabled&#8221;]) print(&#8220;monitor.regex :&#8221;, cfg[&#8220;monitor&#8221;][&#8220;regex&#8221;]) print(&#8220;monitor.thresholds.cpu_max :&#8221;, cfg[&#8220;monitor&#8221;][&#8220;thresholds&#8221;][&#8220;cpu_max&#8221;]) print(&#8220;monitor.thresholds.actions :&#8221;, cfg[&#8220;monitor&#8221;][&#8220;thresholds&#8221;][&#8220;actions&#8221;][&#8220;on_breach&#8221;]) print(&#8220;storage.path (repeated @ -&gt; list):&#8221;, list(cfg[&#8220;storage&#8221;][&#8220;path&#8221;])) cfg[&#8220;port&#8221;] = &#8220;10085&#8221; cfg[&#8220;monitor&#8221;][&#8220;thresholds&#8221;][&#8220;actions&#8221;][&#8220;on_breach&#8221;] = &#8220;restart&#8221; NEW_PATH = CONF_PATH + &#8220;.new&#8221; conf.Dict2Configure(cfg, separator=&#8221;:&#8221;).write_conf(NEW_PATH) re_read = conf.Configure2Dict(NEW_PATH, separator=&#8221;:&#8221;).get_dict() print(&#8220;round-trip port :&#8221;, re_read[&#8220;port&#8221;], &#8220;(was 12345)&#8221;) print(&#8220;round-trip on_breach :&#8221;, re_read[&#8220;monitor&#8221;][&#8220;thresholds&#8221;][&#8220;actions&#8221;][&#8220;on_breach&#8221;], &#8220;(was alert)&#8221;) except Exception as e: skip(e) We move on to CUP decorators and see how they help us create single-instance classes, track execution time, and protect Linux-only functions. We then work with CUP\u2019s rich configuration system and load a nested configuration file with sections, child sections, and repeated values. We also update the configuration and write it back to disk to confirm that the read-modify-write flow works correctly. Caching, IDs, Thread Pools Copy CodeCopiedUse a different Browser banner(&#8220;4. IN-MEMORY KV CACHE (cup.cache)&#8221;) try: from cup import cache kv = cache.KVCache(name=&#8221;demo&#8221;) kv.set({&#8220;user:1&#8221;: &#8220;alice&#8221;, &#8220;user:2&#8221;: &#8220;bob&#8221;}, expire_sec=2) kv.set({&#8220;config:flag&#8221;: &#8220;on&#8221;}, expire_sec=None) print(&#8220;size after sets :&#8221;, kv.size()) print(&#8220;get user:1 :&#8221;, kv.get(&#8220;user:1&#8221;)) print(&#8220;get missing key :&#8221;, kv.get(&#8220;nope&#8221;)) print(&#8220;sleeping 2.2s to let the 2s-TTL keys expire &#8230;&#8221;) time.sleep(2.2) print(&#8220;get user:1 (expired) :&#8221;, kv.get(&#8220;user:1&#8221;)) print(&#8220;get config:flag (eternal):&#8221;, kv.get(&#8220;config:flag&#8221;)) reclaimed = kv.pop_n_expired(0) print(&#8220;pop_n_expired reclaimed :&#8221;, list(reclaimed.keys()) if reclaimed else []) except Exception as e: skip(e) banner(&#8220;5. UNIQUE ID GENERATION (cup.services.generator)&#8221;) try: from cup.services import generator gman = generator.CGeneratorMan() print(&#8220;uniqname :&#8221;, gman.get_uniqname()) print(&#8220;next_uniq_num :&#8221;, gman.get_next_uniq_num()) print(&#8220;next_uniq_num (again) :&#8221;, gman.get_next_uniq_num(), &#8220;(monotonic)&#8221;) if hasattr(gman, &#8220;get_uuid&#8221;): try: print(&#8220;get_uuid :&#8221;, gman.get_uuid()) except Exception as e: skip(e) if hasattr(gman, &#8220;get_random_str&#8221;): try: print(&#8220;get_random_str(16) :&#8221;, gman.get_random_str(16)) except Exception as e: skip(e) print(&#8220;singleton check :&#8221;, generator.CGeneratorMan() is gman) try: cyc = generator.CycleIDGenerator(&#8220;127.0.0.1&#8221;, 8080) i1, i2 = cyc.next_id(), cyc.next_id() print(&#8220;CycleIDGenerator id #1 :&#8221;, i1) print(&#8220;CycleIDGenerator id #2 :&#8221;, i2, &#8220;(incremented)&#8221;) print(&#8220;id #1 as hex :&#8221;, generator.CycleIDGenerator.id2_hexstring(i1)) except Exception as e: skip(e) except Exception as e: skip(e) banner(&#8220;6. THREAD POOL (cup.services.threadpool)&#8221;) try: from cup.services import threadpool pool = threadpool.ThreadPool(minthreads=2, maxthreads=4, name=&#8221;demo-pool&#8221;) pool.start() results, rlock = [], threading.Lock() def square(n): time.sleep(0.03) with rlock: results.append(n * n) return n * n for i in range(8): pool.add_1job(square, i) callback_log = [] def on_done(ok, result): callback_log.append((ok, result)) pool.add_1job_with_callback(on_done, square, 100) def will_fail(): raise RuntimeError(&#8220;boom inside worker&#8221;) pool.add_1job_with_callback(on_done, will_fail) time.sleep(0.5) print(&#8220;live stats :&#8221;, pool.get_stats()) pool.stop() print(&#8220;squares collected :&#8221;, sorted(results)) print(&#8220;callback results :&#8221;, callback_log) except Exception as e: skip(e) We use CUP\u2019s in-memory cache to store key-value pairs with temporary and permanent lifetimes. We then generate unique names, counters, UUID-style values, random strings, and cycling IDs for distributed-style identifiers. We also create a thread pool, submit jobs, collect results, and observe callback behavior for both successful and failed tasks. Threads, Scheduling, Time Utilities Copy CodeCopiedUse a different Browser banner(&#8220;7. INTERRUPTIBLE THREADS + RW LOCK (cup.thread)&#8221;) try: from cup import thread as cupthread rw = cupthread.RWLock() rw.acquire_readlock() rw.acquire_readlock() print(&#8220;acquired 2 read locks concurrently&#8221;) rw.release_readlock() rw.release_readlock() rw.acquire_writelock() print(&#8220;acquired exclusive write lock&#8221;) rw.release_writelock()<\/p>","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"pmpro_default_level":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"_pvb_checkbox_block_on_post":false,"footnotes":""},"categories":[52,5,7,1],"tags":[],"class_list":["post-101208","post","type-post","status-publish","format-standard","hentry","category-ai-club","category-committee","category-news","category-uncategorized","pmpro-has-access"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.3 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit - YouZum<\/title>\n<meta name=\"description\" content=\"\u0e01\u0e34\u0e08\u0e01\u0e23\u0e23\u0e21\u0e40\u0e01\u0e35\u0e48\u0e22\u0e27\u0e01\u0e31\u0e1a\u0e42\u0e14\u0e23\u0e19\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/youzum.net\/fr\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/\" \/>\n<meta property=\"og:locale\" content=\"fr_FR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit - YouZum\" \/>\n<meta property=\"og:description\" content=\"\u0e01\u0e34\u0e08\u0e01\u0e23\u0e23\u0e21\u0e40\u0e01\u0e35\u0e48\u0e22\u0e27\u0e01\u0e31\u0e1a\u0e42\u0e14\u0e23\u0e19\" \/>\n<meta property=\"og:url\" content=\"https:\/\/youzum.net\/fr\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/\" \/>\n<meta property=\"og:site_name\" content=\"YouZum\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DroneAssociationTH\/\" \/>\n<meta property=\"article:published_time\" content=\"2026-07-01T18:44:06+00:00\" \/>\n<meta name=\"author\" content=\"admin NU\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"\u00c9crit par\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin NU\" \/>\n\t<meta name=\"twitter:label2\" content=\"Dur\u00e9e de lecture estim\u00e9e\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/\"},\"author\":{\"name\":\"admin NU\",\"@id\":\"https:\/\/yousum.gpucore.co\/#\/schema\/person\/97fa48242daf3908e4d9a5f26f4a059c\"},\"headline\":\"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit\",\"datePublished\":\"2026-07-01T18:44:06+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/\"},\"wordCount\":679,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/yousum.gpucore.co\/#organization\"},\"articleSection\":[\"AI\",\"Committee\",\"News\",\"Uncategorized\"],\"inLanguage\":\"fr-FR\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/\",\"url\":\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/\",\"name\":\"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit - YouZum\",\"isPartOf\":{\"@id\":\"https:\/\/yousum.gpucore.co\/#website\"},\"datePublished\":\"2026-07-01T18:44:06+00:00\",\"description\":\"\u0e01\u0e34\u0e08\u0e01\u0e23\u0e23\u0e21\u0e40\u0e01\u0e35\u0e48\u0e22\u0e27\u0e01\u0e31\u0e1a\u0e42\u0e14\u0e23\u0e19\",\"breadcrumb\":{\"@id\":\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/#breadcrumb\"},\"inLanguage\":\"fr-FR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/youzum.net\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/yousum.gpucore.co\/#website\",\"url\":\"https:\/\/yousum.gpucore.co\/\",\"name\":\"YouSum\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/yousum.gpucore.co\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/yousum.gpucore.co\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"fr-FR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/yousum.gpucore.co\/#organization\",\"name\":\"Drone Association Thailand\",\"url\":\"https:\/\/yousum.gpucore.co\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"fr-FR\",\"@id\":\"https:\/\/yousum.gpucore.co\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/youzum.net\/wp-content\/uploads\/2024\/11\/tranparent-logo.png\",\"contentUrl\":\"https:\/\/youzum.net\/wp-content\/uploads\/2024\/11\/tranparent-logo.png\",\"width\":300,\"height\":300,\"caption\":\"Drone Association Thailand\"},\"image\":{\"@id\":\"https:\/\/yousum.gpucore.co\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/DroneAssociationTH\/\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/yousum.gpucore.co\/#\/schema\/person\/97fa48242daf3908e4d9a5f26f4a059c\",\"name\":\"admin NU\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"fr-FR\",\"@id\":\"https:\/\/yousum.gpucore.co\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/youzum.net\/wp-content\/uploads\/avatars\/2\/1746849356-bpfull.png\",\"contentUrl\":\"https:\/\/youzum.net\/wp-content\/uploads\/avatars\/2\/1746849356-bpfull.png\",\"caption\":\"admin NU\"},\"url\":\"https:\/\/youzum.net\/fr\/members\/adminnu\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit - YouZum","description":"\u0e01\u0e34\u0e08\u0e01\u0e23\u0e23\u0e21\u0e40\u0e01\u0e35\u0e48\u0e22\u0e27\u0e01\u0e31\u0e1a\u0e42\u0e14\u0e23\u0e19","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/youzum.net\/fr\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/","og_locale":"fr_FR","og_type":"article","og_title":"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit - YouZum","og_description":"\u0e01\u0e34\u0e08\u0e01\u0e23\u0e23\u0e21\u0e40\u0e01\u0e35\u0e48\u0e22\u0e27\u0e01\u0e31\u0e1a\u0e42\u0e14\u0e23\u0e19","og_url":"https:\/\/youzum.net\/fr\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/","og_site_name":"YouZum","article_publisher":"https:\/\/www.facebook.com\/DroneAssociationTH\/","article_published_time":"2026-07-01T18:44:06+00:00","author":"admin NU","twitter_card":"summary_large_image","twitter_misc":{"\u00c9crit par":"admin NU","Dur\u00e9e de lecture estim\u00e9e":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/#article","isPartOf":{"@id":"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/"},"author":{"name":"admin NU","@id":"https:\/\/yousum.gpucore.co\/#\/schema\/person\/97fa48242daf3908e4d9a5f26f4a059c"},"headline":"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit","datePublished":"2026-07-01T18:44:06+00:00","mainEntityOfPage":{"@id":"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/"},"wordCount":679,"commentCount":0,"publisher":{"@id":"https:\/\/yousum.gpucore.co\/#organization"},"articleSection":["AI","Committee","News","Uncategorized"],"inLanguage":"fr-FR","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/","url":"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/","name":"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit - YouZum","isPartOf":{"@id":"https:\/\/yousum.gpucore.co\/#website"},"datePublished":"2026-07-01T18:44:06+00:00","description":"\u0e01\u0e34\u0e08\u0e01\u0e23\u0e23\u0e21\u0e40\u0e01\u0e35\u0e48\u0e22\u0e27\u0e01\u0e31\u0e1a\u0e42\u0e14\u0e23\u0e19","breadcrumb":{"@id":"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/#breadcrumb"},"inLanguage":"fr-FR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/youzum.net\/cup-common-useful-python-building-reliable-python-workflows-with-baidus-utility-toolkit\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/youzum.net\/"},{"@type":"ListItem","position":2,"name":"CUP (Common Useful Python): Building Reliable Python Workflows with Baidu\u2019s Utility Toolkit"}]},{"@type":"WebSite","@id":"https:\/\/yousum.gpucore.co\/#website","url":"https:\/\/yousum.gpucore.co\/","name":"YouSum","description":"","publisher":{"@id":"https:\/\/yousum.gpucore.co\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/yousum.gpucore.co\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"fr-FR"},{"@type":"Organization","@id":"https:\/\/yousum.gpucore.co\/#organization","name":"Drone Association Thailand","url":"https:\/\/yousum.gpucore.co\/","logo":{"@type":"ImageObject","inLanguage":"fr-FR","@id":"https:\/\/yousum.gpucore.co\/#\/schema\/logo\/image\/","url":"https:\/\/youzum.net\/wp-content\/uploads\/2024\/11\/tranparent-logo.png","contentUrl":"https:\/\/youzum.net\/wp-content\/uploads\/2024\/11\/tranparent-logo.png","width":300,"height":300,"caption":"Drone Association Thailand"},"image":{"@id":"https:\/\/yousum.gpucore.co\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DroneAssociationTH\/"]},{"@type":"Person","@id":"https:\/\/yousum.gpucore.co\/#\/schema\/person\/97fa48242daf3908e4d9a5f26f4a059c","name":"admin NU","image":{"@type":"ImageObject","inLanguage":"fr-FR","@id":"https:\/\/yousum.gpucore.co\/#\/schema\/person\/image\/","url":"https:\/\/youzum.net\/wp-content\/uploads\/avatars\/2\/1746849356-bpfull.png","contentUrl":"https:\/\/youzum.net\/wp-content\/uploads\/avatars\/2\/1746849356-bpfull.png","caption":"admin NU"},"url":"https:\/\/youzum.net\/fr\/members\/adminnu\/"}]}},"rttpg_featured_image_url":null,"rttpg_author":{"display_name":"admin NU","author_link":"https:\/\/youzum.net\/fr\/members\/adminnu\/"},"rttpg_comment":0,"rttpg_category":"<a href=\"https:\/\/youzum.net\/fr\/category\/ai-club\/\" rel=\"category tag\">AI<\/a> <a href=\"https:\/\/youzum.net\/fr\/category\/committee\/\" rel=\"category tag\">Committee<\/a> <a href=\"https:\/\/youzum.net\/fr\/category\/news\/\" rel=\"category tag\">News<\/a> <a href=\"https:\/\/youzum.net\/fr\/category\/uncategorized\/\" rel=\"category tag\">Uncategorized<\/a>","rttpg_excerpt":"In this tutorial, we explore CUP, Baidu\u2019s Common Useful Python library, as a practical utility toolkit for building stronger Python workflows. We begin by setting up the library in a Colab-friendly environment and then move through its major subsystems step by step, including logging, decorators, nested configuration, caching, ID generation, thread pools, interruptible threads, delayed\u2026","_links":{"self":[{"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/posts\/101208","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/comments?post=101208"}],"version-history":[{"count":0,"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/posts\/101208\/revisions"}],"wp:attachment":[{"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/media?parent=101208"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/categories?post=101208"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/youzum.net\/fr\/wp-json\/wp\/v2\/tags?post=101208"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}