<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hisham Karam on Medium]]></title>
        <description><![CDATA[Stories by Hisham Karam on Medium]]></description>
        <link>https://medium.com/@hishamkaram?source=rss-f1b3c4c352e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MmKdgkY9Ysr8ZwbaHA_BqA@2x.jpeg</url>
            <title>Stories by Hisham Karam on Medium</title>
            <link>https://medium.com/@hishamkaram?source=rss-f1b3c4c352e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:22:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hishamkaram/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I wanted to ask my coding agent, then let it handle the handoffs]]></title>
            <link>https://medium.com/@hishamkaram/i-wanted-to-ask-my-coding-agent-then-let-it-handle-the-handoffs-b45aab4568f3?source=rss-f1b3c4c352e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b45aab4568f3</guid>
            <dc:creator><![CDATA[Hisham Karam]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 09:23:38 GMT</pubDate>
            <atom:updated>2026-11-18T09:23:38.544Z</atom:updated>
            <content:encoded><![CDATA[<p>I asked Claude to get a second opinion from Codex. Starting the work was easy. Keeping it connected to the original conversation was harder: sometimes the lead lost track of the background job; other times it got stuck in its own monitoring loop.</p><p>I wanted to describe what I needed in the terminal, in ordinary language, and let the lead handle the coordination.</p><p>Something like this:</p><blockquote><strong><em>Me:</em></strong><em> Ask Codex and Claude to review this change independently. Bring me the findings and any decisions you need from me.</em></blockquote><blockquote><strong><em>Lead:</em></strong><em> I’ll prepare the reviews, follow both tasks, and compare the findings.</em></blockquote><p><em>Illustrative conversation, not a recorded run. The wording can vary; the point is that I ask for the work, rather than manage each handoff myself.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qWaAVVeotX7hoswm.png" /></figure><p>That is the experience I built <a href="https://github.com/hishamkaram/delegation-layer">Delegate</a> around. After setup, I stay in my coding agent’s conversation. The lead uses Delegate to assign work, follow it, collect the results, and bring the useful parts back to me.</p><p><a href="https://d8j0ntlcm91z4.cloudfront.net/user_3LW33kOpmPzgu1ixuC4xxRRHWVm/hf_20261101_204620_90a74de4-625a-4b4d-8af5-709f79374793.mp4">Watch the eight-second illustrative review demo</a></p><p><em>This existing animation shows the same idea in a desktop chat interface. It is an illustrative example, not a live recording or the terminal interface shown above.</em></p><h3>The lead should carry the context</h3><p>I know the goal and the constraints. The lead already has the conversation about the change. It should use that context to prepare a focused assignment for another agent, instead of making me explain everything twice.</p><p>When the review comes back, I want the lead to read it, check whether the findings hold up, and connect them to the original request. If a finding needs a correction within the work I authorized, the lead can handle that next step. If the work needs a new decision or permission, it should ask me.</p><p>That is where the integration matters. Delegate provides the task lifecycle and result evidence. The lead’s integration tells it how to use those capabilities and what it must check before saying the work is complete.</p><p>The user-facing interaction stays simple because the coordination has a clear owner.</p><h3>I used it on Delegate itself</h3><p>A recent terminal UI fix gave me a useful example.</p><p>A page-navigation action could be dropped during a background refresh. The correction needed navigation to take priority while preserving the user’s selection when loading failed.</p><p>We reproduced the problem, corrected the implementation, and checked the correction. Sol and Claude Opus independently reviewed the final change. I followed the review from one session.</p><p>What mattered was getting the review back into the work. The regression failed on the first candidate and passed after the correction. The independent approvals supported that evidence; they did not replace it.</p><p>That is the kind of result I want the lead to bring back: what was wrong, what changed, and what was checked.</p><h3>The other features came from the same need</h3><h3>Teams: choose the right model for the phase</h3><p>I do not always want the same model doing every part of a change. I might prefer a stronger model for planning and review, with a less expensive model handling implementation.</p><p>Teams lets me save members, roles, and model choices. With the integration skill, the lead can discover a configured team and select a suitable member without me naming the team each time.</p><p>It is optional. I can delegate without creating a team, and having one does not force the lead to split every request across multiple workers. It gives the lead reusable choices, not a fixed workflow or a promise of lower cost.</p><h3>SSH: use another prepared machine</h3><p>I have more than one machine. When I need more capacity, I want to tell the lead which prepared machine to use and keep working in the same conversation.</p><p>The lead handles the remote assignment and follows the result. The destination needs Delegate and its provider ready beforehand. A connection dropping does not mean the work never started; the existing work still needs to be reconciled.</p><p>Delegate also checks CPU and memory pressure before new tasks or continuations start. Confirmed pressure can cause a refusal. That helps control admission; it does not guarantee that a machine can never run out of memory or automatically move work elsewhere.</p><h3>Schedules: ask once for recurring work</h3><p>Some requests repeat. I wanted to ask the lead to set up the recurring assignment once, then inspect the runs instead of requesting it again every time.</p><p>The schedule needs an independently started scheduler host that stays available. Saving the assignment does not itself start that host or prove that a run succeeded. Those are setup and operational facts the lead needs to report accurately.</p><h3>Gateway: keep the conversation available through MCP</h3><p>I also wanted to reach approved workspaces on my machine from an MCP client through a self-hosted Gateway.</p><p>Once the Gateway, device connector, workspace approvals, and providers are ready, that client can be the entry point to the work. Delegate remains responsible for execution and result evidence. Specific chat or phone apps still need their own compatibility check.</p><h3>Simple to ask, careful underneath</h3><p>The lead needs reliable evidence about whether work was admitted, whether it is still running, and whether a validated result is available. An ended process alone is not enough. Neither is a worker saying “done.”</p><p>Delegate handles the execution lifecycle. The lead still has to read the complete answer and check it against the request. Provider accounts and native permissions remain part of the provider’s setup; Delegate does not add an independent operating-system sandbox.</p><p>I want that care behind the conversation, without making the person asking do the coordination themselves.</p><p>There is still setup, and there are still decisions that need me. But once things are ready, I want to type what I need, let the lead handle the handoffs, and review the result in the same place.</p><p>The <a href="https://github.com/hishamkaram/delegation-layer">repository</a> has the overview and setup guides. If you try it, I would like to hear what you asked your lead to do and where the experience fell short. Issues and pull requests are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b45aab4568f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Codex Duo: Evidence-Based Review, Debate, and Planning]]></title>
            <link>https://medium.com/@hishamkaram/claude-codex-duo-evidence-based-review-debate-and-planning-8736a7f1dcf8?source=rss-f1b3c4c352e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8736a7f1dcf8</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Hisham Karam]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 07:20:09 GMT</pubDate>
            <atom:updated>2026-09-06T07:20:09.906Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Three Claude Code plugins that bring Codex into a structured workflow with independent first passes and written evidence.</em></p><p>I’m actively working on <strong>claude-codex-duo</strong>, an open-source collection of Claude Code plugins for code review, technical debate, and implementation planning with OpenAI Codex.</p><p>The project’s defining rule is that agreement between models does not establish whether a claim is correct. Its review workflow requires findings to be checked against evidence, and its debate workflow records the evidence behind each claim.</p><p>The repository currently contains three independently installable plugins: codex-pr-review, codex-debate, and codex-deep-plan. Each has a separate command and a defined output. <a href="https://github.com/hishamkaram/claude-codex-duo">Project overview</a>.</p><h3>Code review starts with a shared scope</h3><p>codex-pr-review accepts a pull request, branch, commit comparison, or local uncommitted changes. It pins the review scope and builds a neutral brief before findings exist.</p><p>A lead-reviewer agent and Codex receive that brief in separate contexts. Their initial reviews run concurrently. The lead’s findings are sealed, and a join gate checks the required artifacts and hashes before the workflow reads both results together.</p><p>The next phase creates a reconciliation ledger. It records findings raised by both reviewers, findings unique to either reviewer, and disagreements. Duplicate findings are combined only when they share the same root cause and location.</p><p>Selected findings then enter a bounded consultation. Every P0–P3 finding still requires verification, regardless of its source or whether both models agreed. The verification process calls for evidence such as a reproduction, a traced code path, or relevant test results. A withdrawn claim is checked rather than accepted as settled simply because a reviewer retracted it.</p><p>The final report records one merge recommendation under an ordered policy: BLOCK, REQUEST CHANGES, NEEDS CLARIFICATION, APPROVE WITH COMMENTS, or APPROVE. Refuted findings go into a false-positive appendix; unresolved findings remain visible. <a href="https://github.com/hishamkaram/claude-codex-duo/blob/0013184868efe006cafca91a2e0825fc1b2997c5/plugins/codex-pr-review/skills/two-model-pr-review/references/adjudication.md">Review adjudication rules</a>.</p><p>For a local review, the documented command shape is:</p><pre>/codex-pr-review:review-pr local HEAD &quot;Describe the intended change&quot;</pre><p>Replace the quoted text with the actual intent. Local mode snapshots staged, unstaged, deleted, and non-ignored untracked files through a scratch index outside the repository. It leaves the repository’s own index, refs, stash, reflog, and working files unchanged, while adding unreachable Git objects to represent the snapshot. <a href="https://github.com/hishamkaram/claude-codex-duo/blob/0013184868efe006cafca91a2e0825fc1b2997c5/README.md#reviewing-uncommitted-changes">Local review details</a>.</p><h3>Technical debate keeps a claim ledger</h3><p>codex-debate handles a falsifiable motion or a choice between named options. It provides three modes: challenge, compare, and hypothesis.</p><p>An illustrative comparison command is:</p><pre>/codex-debate:debate &quot;Option A: Redis streams vs Option B: Postgres outbox for the job queue&quot; compare 2</pre><p>This is an invocation example, not a recommendation for either architecture.</p><p>Each claim receives an ID, owner, evidence grade, and status. The grades distinguish executed evidence, traced source, cited documents, reasoning, and unsupported assertions. Unsupported assertions cannot decide the ruling.</p><p>Replies must maintain a claim with evidence, retract it because of a specific fact, refine it, or commit to a concrete verification step. The protocol also defines stopping conditions and permits an unresolved result. Its final ruling includes the surviving counterargument and recorded concessions. <a href="https://github.com/hishamkaram/claude-codex-duo/blob/0013184868efe006cafca91a2e0825fc1b2997c5/plugins/codex-debate/skills/codex-debate/references/protocol.md">Debate protocol</a>.</p><h3>Planning separates facts from inferences</h3><p>codex-deep-plan accepts issue references, PR review comments, individual comment URLs, plain requests, and request files. Its evidence rules distinguish four categories: facts read at a pinned revision, results observed through execution, inferences, and unknowns.</p><p>The workflow includes citation checks that resolve source references at the pinned commit and compare quoted text. Decisions require fact or execution evidence; an inference alone is insufficient support.</p><p>Codex receives an independent diagnosis brief, followed by a bounded exchange over differences. The requested depth determines the process: a question produces an evidence-backed answer, while a change request produces a plan. Multiple inputs do not automatically become one PR; the workflow checks whether they share a cause or change surface.</p><p>For example:</p><pre>/codex-deep-plan:plan &quot;add rate limiting to the export endpoint&quot; --rounds 1</pre><p>The example requests a plan. It does not implement rate limiting. The documented handoff places the resulting change plan into Claude Code plan mode when that interface is available. <a href="https://github.com/hishamkaram/claude-codex-duo/blob/0013184868efe006cafca91a2e0825fc1b2997c5/plugins/codex-deep-plan/commands/plan.md">Planning command</a> and <a href="https://github.com/hishamkaram/claude-codex-duo/blob/0013184868efe006cafca91a2e0825fc1b2997c5/plugins/codex-deep-plan/skills/deep-plan-duo/references/evidence-rules.md">evidence rules</a>.</p><h3>The boundaries matter</h3><p>The project describes its blind-review separation as <strong>procedural, not structural</strong>. Codex’s sandbox can read temporary files and Claude Code transcripts. Independence relies on the neutral brief, separate initial contexts, sealed artifacts, and phase ordering; it is not a filesystem isolation guarantee.</p><p>The plugins are designed for read-only work on the reviewed checkout. They write evidence artifacts outside the repository, and deep planning can write the plan-mode handoff file. Local review also creates the unreachable Git objects described above.</p><p>Using Codex sends repository content to OpenAI. The documented workflow asks whether that is permitted before the first Codex call. If Codex is unavailable, the workflow reports the reduced mode instead of simulating a second model. <a href="https://github.com/hishamkaram/claude-codex-duo/blob/0013184868efe006cafca91a2e0825fc1b2997c5/README.md">Boundaries and prerequisites</a>.</p><h3>Installation and a first run</h3><p>Prerequisites include Claude Code with plugins enabled, the configured OpenAI Codex plugin, Git, Python 3, and Node. GitHub-based inputs also use gh. The repository documents macOS and Linux support; Windows local review is untested.</p><p>Set up the Codex dependency using the repository’s prerequisite instructions, then add the marketplace and install the workflows you need:</p><pre>claude plugin marketplace add hishamkaram/claude-codex-duo<br>claude plugin install codex-pr-review@claude-codex-duo --scope user<br>claude plugin install codex-debate@claude-codex-duo --scope user<br>claude plugin install codex-deep-plan@claude-codex-duo --scope user</pre><p>The <a href="https://github.com/hishamkaram/claude-codex-duo">repository</a> provides the full setup, commands, artifact layouts, troubleshooting guide, and MIT license. Start with a scoped review or a concrete technical question, then inspect the resulting evidence alongside the recommendation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8736a7f1dcf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code Router: Multiple Model Providers in One Claude Code Session]]></title>
            <link>https://medium.com/@hishamkaram/claude-code-router-multiple-model-providers-in-one-claude-code-session-57e2807581a7?source=rss-f1b3c4c352e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/57e2807581a7</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Hisham Karam]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 07:19:52 GMT</pubDate>
            <atom:updated>2026-09-06T07:29:38.534Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A local Go gateway for explicit model selection, capability checks, and visible routing.</em></p><p>I’m actively working on <strong>Claude Code Router</strong>, an open-source project that connects Claude Code to first-party Anthropic models and configured external providers through a local gateway.</p><p>The command-line tool is called ccr. Claude Code connects to its loopback address, and CCR routes requests to the selected model. Supported provider profiles include OpenRouter, Z.AI, LiteLLM, and trusted local OpenAI-compatible endpoints. The gateway exits when the Claude Code process it launched exits.</p><p>This article walks through the project’s documented workflow: configure a provider, register model aliases, switch routes within a session, and inspect what happened. <a href="https://github.com/hishamkaram/claude-code-router">Project overview</a>.</p><h3>One session, explicit model selection</h3><p>CCR separates a <strong>provider connection</strong> from a <strong>model alias</strong>. The connection defines the endpoint and credential source. The alias names a model route that you can select from Claude Code.</p><p>That separation lets a workflow keep using an alias while its configured provider model changes. In a session with preserved Claude authentication, eligible aliases appear alongside permitted Anthropic models in the /model picker. CCR also prints their exact picker IDs at launch.</p><p>Switching changes the route used for subsequent work where Claude Code permits it. New subagents and workflows can inherit the active model; existing workers can remain on their original model. Picker entries are generated at launch, so changes to aliases or capability metadata require a relaunch to refresh the visible choices. <a href="https://github.com/hishamkaram/claude-code-router/blob/8dd17b7d16c1a8099a643e365248d41bd04e58f1/docs/routing.md">Routing documentation</a>.</p><figure><img alt="Animated terminal recording: browsing Claude Code’s /model picker, selecting anthropic.ccr.litellm-grok-4–6, then sending “hi” and receiving a reply in the same session." src="https://cdn-images-1.medium.com/max/1024/1*PB9bV5m9izXr_LClvHUq7A.gif" /><figcaption>Selecting a registered CCR alias in /model and continuing the conversation. Cropped excerpt; 1.5× playback.</figcaption></figure><h3>Compatibility is part of the route</h3><p>CCR tracks provider and model capabilities before forwarding requests. Effective model facts follow a defined order: local overrides, provider discovery, then recognized model hints. Missing metadata remains unknown.</p><p>An imported model starts with degraded compatibility status. Importing it does not automatically certify every feature. Other statuses include full, chat-only, and blocked; a chat-only launch disables Claude Code tools, while blocked aliases are refused.</p><p>For example, the documented image-input path requires both a translatable image request and an effective capability allowing image input. If those conditions are not met, CCR rejects the request. It does not remove the image or silently send the request to another model.</p><p>OpenAI Responses support is also explicit. An OpenAI-compatible endpoint is not automatically treated as a Responses endpoint. The provider and alias must be configured for that route. Managed computer use adds another requirement: an explicitly selected supported executor.</p><p>These rules describe compatibility boundaries, not a promise that every provider implements every Claude Code feature. <a href="https://github.com/hishamkaram/claude-code-router/blob/8dd17b7d16c1a8099a643e365248d41bd04e58f1/docs/providers.md">Provider and capability reference</a>.</p><h3>Getting started</h3><p>Claude Code must already be installed and available as claude. On macOS, the documented Homebrew installation is:</p><pre>brew install hishamkaram/tap/claude-code-router<br>ccr version<br>ccr doctor</pre><p>ccr doctor checks the local setup; it is offline by default. Then configure a provider:</p><pre>ccr init<br>ccr provider add --interactive<br>ccr model list</pre><p>The wizard guides you through the provider profile, connection details, credential source, and model aliases. Providers with discovery expose a searchable model selection flow; other profiles use manual model entry. Nothing is saved until the final review completes.</p><p>With working Claude subscription or Anthropic API authentication, launch with:</p><pre>ccr launch</pre><p>To start on a configured provider alias, use:</p><pre>ccr launch --model &lt;alias&gt;</pre><p>Replace &lt;alias&gt; with a name from your model list. The default authentication mode preserves available Claude authentication. Without Claude authentication, an explicit provider alias allows a provider-only launch; omitting both causes launch to fail visibly. <a href="https://github.com/hishamkaram/claude-code-router/blob/8dd17b7d16c1a8099a643e365248d41bd04e58f1/docs/getting-started.md">Getting-started guide</a>.</p><h3>Inspect the route, not the model’s self-description</h3><p>CCR exposes commands for inspecting configuration, compatibility, and runtime activity:</p><pre>ccr model show &lt;alias&gt; --json<br>ccr model test &lt;alias&gt;<br>ccr conformance run &lt;alias&gt;<br>ccr status<br>ccr trace --follow</pre><p>The live checks contact the configured provider. Runtime records expose the observed alias, provider model, protocol, result, latency, and provider-reported token usage when available. CCR does not estimate monetary cost.</p><p>The routing documentation explicitly distinguishes those observations from a model’s generated answer about its own identity. A sentence in a conversation is not the route record. <a href="https://github.com/hishamkaram/claude-code-router/blob/8dd17b7d16c1a8099a643e365248d41bd04e58f1/docs/routing.md#runtime-and-lifecycle-visibility">Runtime visibility</a>.</p><h3>Local state and credentials</h3><p>CCR uses SQLite for configuration and redacted operational metadata. Its documented credential choices are environment-variable references, permission-restricted key files, and the OS keychain. Raw API keys are not stored in SQLite.</p><p>The documented route-history policy excludes prompts, responses, tool arguments, and authorization headers. Configuration exports also exclude credential values, keychain identifiers, and key-file paths; credentials are bound separately on the importing machine. <a href="https://github.com/hishamkaram/claude-code-router/blob/8dd17b7d16c1a8099a643e365248d41bd04e58f1/docs/providers.md">Credential handling and team profiles</a>.</p><h3>Explore the project</h3><p>Claude Code Router brings provider configuration, model selection, compatibility checks, and route inspection into one local tool. It is written in Go and released under the MIT license.</p><p>The <a href="https://github.com/hishamkaram/claude-code-router">repository</a> includes installation instructions, release notes, and contribution guidelines. If you try a provider route, reproducible compatibility reports are welcome: include the CCR version, model alias, and redacted diagnostic output, without credentials or private prompts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57e2807581a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[introduction to Jira Automation]]></title>
            <link>https://medium.com/anymind-group/introduction-to-jira-automation-a2086e7c37a?source=rss-f1b3c4c352e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2086e7c37a</guid>
            <category><![CDATA[jira-cloud]]></category>
            <category><![CDATA[jira-software]]></category>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Hisham Karam]]></dc:creator>
            <pubDate>Mon, 17 Oct 2022 06:08:00 GMT</pubDate>
            <atom:updated>2022-10-17T06:16:45.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*76ETKHzVB8Dq3FdxPdR5hw@2x.png" /></figure><p>in this article we will cover what is Jira Automation, some Jira Automation concepts and an example for how to create a Jira Automation Rule for example: if the a pull request is merged to staging branch move the related ticket from IN-REVIEW status to QC TESTINGstatus. let’s get starting</p><h3>What is Jira Automation ?</h3><p>Automation is a no-code rule builder that enables customers to build if-this-then-that-rules based on events in Jira. It allows teams to automate their processes, save time, keep Jira up to date and focus on what’s most important.</p><h3>Key concepts</h3><h4>Rules:</h4><p>Rules allow you to automate actions within your system based on criteria that you set. rule example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*PqUwWzVGsh-DtblzRW_bpA.png" /></figure><p>Automation rules are made up of three parts: <br>1. triggers that kick off the rule.<br>2. conditions that refine the rule.<br>3. actions that perform tasks in your site.</p><h4>Triggers:</h4><p>Every rule starts with a trigger. They kick off the execution of your rules, for example: ISSUE CREATED. you can find list of triggers <a href="https://support.atlassian.com/cloud-automation/docs/jira-automation-triggers/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wMYX-qJCFW-3iPR0kb3lA.png" /></figure><h4>Conditions:</h4><p>Conditions allow you to narrow the scope of your rule. They must be met for your rule to continue running. For example: you can check if the issue is status equals to IN REVIEW . you find list of available conditions <a href="https://support.atlassian.com/cloud-automation/docs/jira-automation-conditions/">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWhABSa0wvCHP5bCrB-tgQ.png" /></figure><p>If a condition fails, the rule will stop running and no actions following the condition will be performed.</p><h4>Actions:</h4><p>Actions are the doers of your rule. They allow you to automate tasks and make changes within your site. They allow you to perform many tasks, such as sending an email, editing issue and create a new branch. you can find list of available actions <a href="https://support.atlassian.com/cloud-automation/docs/jira-automation-actions/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuTad2b9NKqrX1kkpFpfOQ.png" /></figure><h3>How to create a Rule ?</h3><p>Consider the following scenario. Currently, when a pull request is merged to staging branch, we move the related ticket from IN REVIEW to QC TESTING. This process can be automated easily, We can create a simple rule to automatically move the ticket from IN REVIEW to QC TESTINGif the ticket’s pull request is merged to staging.</p><ol><li>Open Your Project settings.</li><li>Navigate to your Automation settings and select Create rule in the top-right corner.</li><li>Select the Pull request merged trigger, and select Save.</li><li>Select New condition, and select the Advanced compare condition.</li><li>Configure the condition as follows:<br>Set the First Field to <a href="https://support.atlassian.com/cloud-automation/docs/what-are-smart-values/">{{pullRequest.destinationBranch.name}}</a> <br>Set the Condition to equals<br>Set the Second Value to compare to your staging branch name ex: staging<br>Select Save.</li><li>Select New condition, and select the Issue fields condition.</li><li>Configure the condition as follows:<br>Set the Field to Status<br>Set the Condition to equals<br>Set the Value to compare to IN REVIEW<br>Select Save.</li><li>Select New action, and select the Transition the issue to action.</li><li>Configure the action as follows:<br>Set the Destination Status to QC TESTING <br>Select Save</li><li>Give your rule a name, and select Turn it on.</li></ol><p><strong>you can the template library from </strong><a href="https://www.atlassian.com/software/jira/automation-template-library"><strong>here</strong></a><strong> . those templates can help you to create your own rule</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2086e7c37a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/anymind-group/introduction-to-jira-automation-a2086e7c37a">introduction to Jira Automation</a> was originally published in <a href="https://medium.com/anymind-group">AnyMind Group</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Python Descriptors]]></title>
            <link>https://medium.com/anymind-group/the-power-of-python-descriptors-d95c18517fed?source=rss-f1b3c4c352e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d95c18517fed</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hisham Karam]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 07:19:05 GMT</pubDate>
            <atom:updated>2022-07-01T09:02:08.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ztUDgjkxukKJqhMTlizyjA.png" /><figcaption><a href="https://docs.python.org/3/glossary.html#term-descriptor">Descriptors</a> let objects customize attribute lookup, storage, and deletion.</figcaption></figure><h3>What are Python Descriptors?</h3><p>Python <a href="https://docs.python.org/3/glossary.html#term-descriptor">descriptor</a> protocol is a way to specify what happens when an attribute is referenced on a model. It allows you to easily manage attribute access :</p><ul><li>get access by implementing __get__ method in the Descriptor where __get__ accesses the attribute. It returns the value of the attribute, or raise the AttributeError exception if a requested attribute is not present.</li><li>set access by implementing __set__ method in the Descriptor where __set__ is called in an attribute assignment operation. Returns None.</li><li>delete access by implementing __delete__ method in the Descriptor __delete__ controls a delete operation. Returns None.</li></ul><h3>When can we use the Descriptors ?</h3><p>we can use the Descriptors to validate the attribute value before value assignment ex: consider a phone_number attribute. the verification of the correct phone number format is required before assigning a value to that attribute. the descriptor allows phone_number to be processed through a regular expression and its format validated before assigning it to an attribute.</p><h3>How can we define and use the Descriptors ?</h3><p>let say we have a class named Employee which contains an attribute for employee’s salary and we need to check if the salary value is a Number before assigning the value to the salary attribute.</p><p>we have two ways to define a descriptor</p><ul><li>defining a new class</li><li>using <a href="https://docs.python.org/3/library/functions.html#property">property</a></li></ul><p><strong>let’s try to write a descriptor to validate the salary attribute value using classes:</strong></p><pre>import numbers</pre><pre>class NumberField:<br>    def __get__(self, obj, obj_type=None):<br>        return obj._salary</pre><pre>    def __set__(self, obj, value):<br>        if not isinstance(value, numbers.Number):<br>            raise TypeError(f&quot;{value} is not a number&quot;)<br>        obj._salary = value</pre><pre>    def __delete__(self, obj):<br>        del obj._salary</pre><pre>class Employee:<br>    salary = NumberField()</pre><p>Let’s test this descriptor:</p><pre>In [2]: hesham = Employee()</pre><pre># NOTE: assignment calls __set__ in the descriptor</pre><pre>In [3]: hesham.salary = 200</pre><pre># NOTE: print calls __get__ in the descriptor</pre><pre>In [4]: print(hesham.salary)</pre><pre># NOTE: del calls __delete__ in the descriptor</pre><pre>In [5]: del hesham.salary</pre><p>now let’s try to assign an invalid value for the salary attribute</p><pre>In [6]: wakita = Employee()</pre><pre># NOTE: wakita.salary = &quot;two hundreds&quot;<br>---------------------------------------------------------------------------<br>TypeError                                 Traceback (most recent call last)<br>Input In [7], in &lt;cell line: 2&gt;()<br>      1 # the following will raise a TypeError exception<br>----&gt; 2 wakita.salary = &quot;two hundreds&quot;</pre><pre>Input In [1], in NumberField.__set__(self, obj, value)<br>     11 if not isinstance(value, numbers.Number):<br>---&gt; 12     raise TypeError(f&#39;{value} is not a number&#39;)<br>     13 obj._salary = value</pre><pre>TypeError: two hundreds is not a number</pre><p><strong>let’s try to write a descriptor to validate the salary attribute value using property:</strong></p><pre>import numbers</pre><pre>class Employee:<br>    def get_salary(self):<br>        return self._salary</pre><pre>    def set_salary(self, value):<br>        if not isinstance(value, numbers.Number):<br>            raise TypeError(f&#39;{value} is not a number&#39;)<br>        self._salary = value</pre><pre>    def delete_salary(self):<br>        del self._salary</pre><pre>    salary = property(get_salary, set_salary, delete_salary)</pre><p>Let’s test this descriptor:</p><pre>In [3]: hesham = Employee()</pre><pre># NOTE: assignment calls set_salary method</pre><pre>In [4]: hesham.salary = 200</pre><pre># NOTE: print calls set_salary method</pre><pre>In [5]: print(hesham.salary)<br>200</pre><pre># NOTE: del calls delete_salary method</pre><pre>In [6]: del hesham.salary</pre><p>now let’s try to assign an invalid value for the salary attribute</p><pre>In [7]: wakita = Employee()</pre><pre>In [8] # the following will raise a TypeError exception</pre><pre>In [9]: wakita.salary = &quot;200&quot;<br>---------------------------------------------------------------------------<br>TypeError                                 Traceback (most recent call last)<br>Input In [9], in &lt;cell line: 1&gt;()<br>----&gt; 1 wakita.salary = &quot;200&quot;</pre><pre>Input In [2], in Employee.set_salary(self, value)<br>      5 def set_salary(self, value):<br>      6     if not isinstance(value, numbers.Number):<br>----&gt; 7         raise TypeError(f&#39;{value} is not a number&#39;)<br>      8     self._salary = value</pre><pre>TypeError: 200 is not a number</pre><h3>How can we a Descriptor with Customized attribute names?</h3><p>in the previous NumberField Descriptor the attribute name is hard-coded _salary . When a class uses descriptors, it can inform each descriptor about which variable name was used.</p><p>In the following example, the Employee class has two descriptor instances, name and address. When the Employee class is defined, it makes a callback to __set_name__ in StringField so that the field names can be recorded.</p><pre>class StringField:<br>    def __set_name__(self, owner, name):<br>        self.attr_name = &#39;_&#39; + name</pre><pre>    def __get__(self, obj, obj_type=None):<br>        print(f&#39;__get__ method attribute name: {self.attr_name}&#39;)<br>        value = getattr(obj, self.attr_name)<br>        return value</pre><pre>    def __set__(self, obj, value):<br>        print(f&#39;__set__ method attribute name: {self.attr_name}, value: {value}&#39;)<br>        if not isinstance(value, str):<br>            raise TypeError(f&#39;{value} is not a string value&#39;)<br>        setattr(obj, self.attr_name, value)</pre><pre>    def __delete__(self, obj):<br>        print(f&#39;__delete__ method attribute name: {self.attr_name}&#39;)<br>        delattr(obj, self.attr_name)</pre><pre>class Employee:<br>    # NOTE: the following descriptor is for name attribute</pre><pre>    name = StringField()</pre><pre>    # NOTE: the following descriptor is for address attribute</pre><pre>    address = StringField()</pre><p>let’s test our descriptor:</p><pre>In [2]: emp1 = Employee()</pre><pre>In [3]: emp1.name = &quot;hesham&quot;<br>__set__ method attribute name: _name, value: hesham # NOTE: attribute name is `_name`</pre><pre>In [4]: emp1.address = &quot;Cairo, Egypt&quot;<br>__set__ method attribute name: _address, value: Cairo, Egypt # NOTE: attribute name is `_address`</pre><pre>In [5]: print(emp1.name)<br>__get__ method attribute name: _name<br>hesham</pre><pre>In [6]: print(emp1.address)<br>__get__ method attribute name: _address<br>Cairo, Egypt</pre><p><strong>NOTE: Descriptors can be used to limit the access for an attribute ex: read-only attribute or write-only attribute</strong></p><h3>Conclusion</h3><p>Python descriptors are powerful and flexible for attribute management but use them with carefully to avoid unnecessary code complexity stemming from overriding the normal behaviors of an object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d95c18517fed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/anymind-group/the-power-of-python-descriptors-d95c18517fed">The Power of Python Descriptors</a> was originally published in <a href="https://medium.com/anymind-group">AnyMind Group</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Tech Blog] What are `__slots__` in python?]]></title>
            <link>https://medium.com/anymind-group/tech-blog-what-are-slots-in-python-fe833c2e0c6d?source=rss-f1b3c4c352e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe833c2e0c6d</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Hisham Karam]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 10:54:27 GMT</pubDate>
            <atom:updated>2022-03-22T10:54:27.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeVZq1JRi5n7Av8b5mmK4g.png" /></figure><p><a href="https://docs.python.org/3.9/reference/datamodel.html#slots">__slots__</a> is a special attribute which is <strong>only</strong> used on class level (the context of Python classes). __slots__ is a class variable that is usually assigned a sequence of strings that are variable names used by instances. for Example:</p><pre>In [1]: class MyClass:<br>   ...:     __slots__ = (&#39;var1&#39;, &quot;var2&quot;)<br>   ...: <br>   ...:     def __init__(self):<br>   ...:         self.var1 = &#39;Hesham&#39;<br>   ...:         self.var2 = &#39;Karm&#39;<br>   ...:</pre><pre>In [2]: obj = MyClass()</pre><pre>In [3]: obj.var1<br>Out[3]: &#39;Hesham&#39;</pre><pre>In [4]: obj.var2<br>Out[4]: &#39;Karm&#39;</pre><p><em>__slots__</em> allow us to explicitly declare data members (like properties) and deny the creation of __dict__and __weakref__(unless explicitly declared in <em>__slots__</em> or available in a parent.)</p><h3>Why should we use __slots__ ?</h3><p>slots are more efficient in terms of memory space and speed of access and a bit safer than the default Python method of data access.</p><ul><li>we can verify if __slots__ are faster (attribute access) using the following code snippet:</li></ul><pre>In [1]: import timeit<br>    ...: <br>    ...: class MySlotClass:<br>    ...:     __slots__ = (&#39;a&#39;,)<br>    ...: <br>    ...: class MyDictClass:<br>    ...:     pass<br>    ...: <br>    ...: slot_obj = MySlotClass()<br>    ...: dict_obj = MyDictClass()<br>    ...: <br>    ...: def test_set_get_del_attr(instance):<br>    ...:     def _benchmark():<br>    ...:         instance.a = &#39;Hesham Karm&#39;<br>    ...:         instance.a<br>    ...:         del instance.a<br>    ...:     return _benchmark<br>    ...: <br>    ...: slots_min_time = min(timeit.repeat(test_set_get_del_attr(slot_obj)))<br>    ...: dict_min_time = min(timeit.repeat(test_set_get_del_attr(dict_obj)))</pre><pre>In [54]: slots_min_time<br>Out[54]: 0.6991060829998332</pre><pre>In [55]: dict_min_time<br>Out[55]: 0.7252470000000812</pre><ul><li>we can verify if __slots__ can save memory by using the following code snippet:</li></ul><pre>In [1]: from pympler.asizeof import asizesof</pre><pre>In [2]: class MySlotClass:<br>   ...:     __slots__ = (&#39;a&#39;, &#39;b&#39;)<br>   ...:     def __init__(self):<br>   ...:         self.a = &#39;Hesham&#39;<br>   ...:         self.b = &#39;Karm&#39;<br>   ...:</pre><pre>In [3]: class MyDictClass:<br>   ...:     def __init__(self):<br>   ...:         self.a = &#39;Hesham&#39;<br>   ...:         self.b = &#39;Karm&#39;<br>   ...:</pre><pre>In [4]: asizesof(MySlotClass())<br>Out[4]: (160,)</pre><pre>In [5]: asizesof(MyDictClass())<br>Out[5]: (376,)<br>In [6]: slot_seq, dict_seq = [], []<br>   ...: for _ in range(10000):<br>   ...:     slot_seq.append(MySlotClass())<br>   ...:     dict_seq.append(MyDictClass())<br>   ...:</pre><pre>In [7]: asizesof(slot_seq)<br>Out[7]: (565288,)</pre><pre>In [8]: asizesof(dict_seq)<br>Out[8]: (1605400,)</pre><blockquote>NOTE: I didn’t use sys.getsizeof because sys.getsizeof works for builtin objects directly, but it does not account for what those objects may contain, specifically, what types, such as custom objects, tuples, lists, dicts, and sets contain. They can contain instances each other, as well as numbers, strings and other objects. more details <a href="https://stackoverflow.com/a/30316760/6222397">here</a>. you can find the package which i used to measure the size of the objects <a href="https://pypi.org/project/Pympler/">here</a></blockquote><p>By default, when Python creates a new instance of a class, it creates a __dict__ attribute for the class. The __dict__ attribute is a dictionary whose keys are the variable names and whose values are the variable values. This allows for dynamic variable creation but can also lead to uncaught errors. For example, with the default __dict__, a misspelled variable name results in the creation of a new variable, but with __slots__ it raises in an AttributeError.</p><pre>In [1]: class MySlotClass:<br>   ...:     __slots__ = (&#39;my_var&#39;,)<br>   ...:     def __init__(self) -&gt; None:<br>   ...:         self.my_var = &#39;Hesham&#39;<br>   ...: <br>   ...: class MyDictClass:<br>   ...:     def __init__(self) -&gt; None:<br>   ...:         self.my_var = &#39;Hesham&#39;<br>   ...:</pre><pre>In [2]: dict_obj = MyDictClass()</pre><pre>In [3]: dict_obj.myvar = &#39;the variable name is misspelled&#39; ✅ # this works fine with normal classes which use __dict__</pre><pre>In [4]: slot_obj = MySlotClass()</pre><pre>In [5]: slot_obj.myvar = &#39;the variable name is misspelled&#39; ❌ # this raise an error with classes which use __slots__<br>---------------------------------------------------------------------------<br>AttributeError                            Traceback (most recent call last)<br>Input In [5], in &lt;cell line: 1&gt;()<br>----&gt; 1 slot_obj.myvar = &#39;the variable name is misspelled&#39;</pre><pre>AttributeError: &#39;MySlotClass&#39; object has no attribute &#39;myvar&#39;</pre><h3>Limitations</h3><p>when Nonempty __slots__ are the same for multiple parents, we can not use multiple inheritance with those parent classes for example:</p><pre>In [1]: class MyDictClassA:<br>   ...:     def __init__(self) -&gt; None:<br>   ...:         self.a = &#39;Hesham&#39;<br>   ...:</pre><pre>In [2]: class MyDictClassB:<br>   ...:     def __init__(self) -&gt; None:<br>   ...:         self.a = &#39;Karm&#39;<br>   ...:<br># NOTE: multiple inheritance works fine with normal classes (__dict__) 👇</pre><pre>In [3]: class MyDictChildClass(MyDictClassA, MyDictClassB): <br>   ...:     pass<br>   ...:</pre><pre># NOTE: multiple inheritance raise an error in case of slots are the same in parent classes 👇</pre><pre>In [4]: class MySlotClassA:<br>   ...:     __slots__ = (&#39;my_var&#39;,)<br>   ...:     def __init__(self) -&gt; None:<br>   ...:         self.my_var = &#39;Hesham&#39;<br>   ...:</pre><pre>In [5]: class MySlotClassB:<br>   ...:     __slots__ = (&#39;my_var&#39;, &#39;b&#39;)<br>   ...:     def __init__(self) -&gt; None:<br>   ...:         self.my_var = &#39;Hesham&#39;<br>   ...:</pre><pre>In [6]: class MySlotChildClass(MySlotClassA, MySlotClassB):<br>   ...:     pass<br>   ...: <br>---------------------------------------------------------------------------<br>TypeError                                 Traceback (most recent call last)<br>Input In [6], in &lt;cell line: 1&gt;()<br>----&gt; 1 class MySlotChildClass(MySlotClassA, MySlotClassB):<br>      2     pass</pre><pre>TypeError: multiple bases have instance lay-out conflict</pre><h3>Conclusion</h3><p>Using __slots__is straightforward. They are a simple, efficient, and safe alternative to Python’s default method of data access. The only known exception is when another object requires access to the __dict__ attribute.</p><p>please check Notes on using __slots__ <a href="https://docs.python.org/3.9/reference/datamodel.html#notes-on-using-slots">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe833c2e0c6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/anymind-group/tech-blog-what-are-slots-in-python-fe833c2e0c6d">[Tech Blog] What are `__slots__` in python?</a> was originally published in <a href="https://medium.com/anymind-group">AnyMind Group</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Tech Blog] Magic (“dunder”) Methods in Python]]></title>
            <link>https://medium.com/anymind-group/magic-methods-dunder-in-python-1e68452edb6?source=rss-f1b3c4c352e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e68452edb6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[magic-method]]></category>
            <category><![CDATA[special-methods]]></category>
            <dc:creator><![CDATA[Hisham Karam]]></dc:creator>
            <pubDate>Wed, 08 Dec 2021 07:03:29 GMT</pubDate>
            <atom:updated>2021-12-10T02:52:07.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixPcZpTRk2iCR76ffd6WmA.png" /><figcaption>Python Magic (“dunder”) Methods</figcaption></figure><p>Magic methods in Python are the special methods which start and end with double underscores __. Usually Magic methods are not being invoked directly by your code but the invocation happens internally from the class on a certain action.</p><p>In Python built-in classes have many magic method. we can use dir function to list the attributes and methods (including magic methods) of any object. For example the following lists all the attributes and methods defined in the str class.</p><pre>&gt;&gt;&gt; dir(str)<br>[&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__dir__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;, &#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__getnewargs__&#39;, &#39;__gt__&#39;, &#39;__hash__&#39;, &#39;__init__&#39;, &#39;__init_subclass__&#39;, &#39;__iter__&#39;, &#39;__le__&#39;, &#39;__len__&#39;, &#39;__lt__&#39;, &#39;__mod__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;, &#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__rmod__&#39;, &#39;__rmul__&#39;, &#39;__setattr__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;, &#39;__subclasshook__&#39;, &#39;capitalize&#39;, &#39;casefold&#39;, &#39;center&#39;, &#39;count&#39;, &#39;encode&#39;, &#39;endswith&#39;, &#39;expandtabs&#39;, &#39;find&#39;, &#39;format&#39;, &#39;format_map&#39;, &#39;index&#39;, &#39;isalnum&#39;, &#39;isalpha&#39;, &#39;isascii&#39;, &#39;isdecimal&#39;, &#39;isdigit&#39;, &#39;isidentifier&#39;, &#39;islower&#39;, &#39;isnumeric&#39;, &#39;isprintable&#39;, &#39;isspace&#39;, &#39;istitle&#39;, &#39;isupper&#39;, &#39;join&#39;, &#39;ljust&#39;, &#39;lower&#39;, &#39;lstrip&#39;, &#39;maketrans&#39;, &#39;partition&#39;, &#39;removeprefix&#39;, &#39;removesuffix&#39;, &#39;replace&#39;, &#39;rfind&#39;, &#39;rindex&#39;, &#39;rjust&#39;, &#39;rpartition&#39;, &#39;rsplit&#39;, &#39;rstrip&#39;, &#39;split&#39;, &#39;splitlines&#39;, &#39;startswith&#39;, &#39;strip&#39;, &#39;swapcase&#39;, &#39;title&#39;, &#39;translate&#39;, &#39;upper&#39;, &#39;zfill&#39;]</pre><p>As you can see above, the str class includes various magic methods surrounded by double underscores. For example the __contains__ method is a magic method which gets called when we check string contains a substring using the in keyword.</p><pre>&gt;&gt;&gt; name = &#39;Hesham Karm&#39;<br>&gt;&gt;&gt; name.__contains__(&#39;Karm&#39;)<br>True<br>&gt;&gt;&gt; &#39;Karm&#39; in name<br>True</pre><p>As you can see, when you do &#39;Karm&#39; in name , the in keyword calls the __contain__(&#39;Karm&#39;) . However, as mentioned before, magic methods are not meant to be called directly, but internally, through some other methods or actions.</p><p>Magic methods are most commonly used to define overloaded behavior of predefined operators in Python. For example, arithmetic operators handle numeric operands by default. This means that numeric objects must be used in combination with operators such as *, /, +, -. The + operator is also defined as a concatenation operator for strings, lists, and tuple classes. It can be said that the + operator is overloaded. Consider the following example</p><pre>&gt;&gt;&gt; class Employee:<br>...     def __init__(self, name, age, salary, currency=&#39;$&#39;):<br>...         self.name = name<br>...         self.age = age<br>...         self.salary = salary<br>...         self.currency = currency<br>...     def __str__(self):<br>...         return f&#39;name: {self.name}, age: {self.age}, salary: {self.salary}{self.currency}&#39;<br>... <br>&gt;&gt;&gt; employee1 = Employee(&#39;Hesham Karm&#39;, 27, 200)<br>&gt;&gt;&gt; print(employee1)<br>name: Hesham Karm, age: 27, salary: 200$</pre><p>as you can see above, the __str__ method is overridden to return a printable string representation of any user defined class (Employee).</p><p>let’s add the __ge__ method to Employee class to overload the &gt;= operator to compare two employees salary:</p><pre>&gt;&gt;&gt; class Employee:<br>...     def __init__(self, name, age, salary, currency=&#39;$&#39;):<br>...         self.name = name<br>...         self.age = age<br>...         self.salary = salary<br>...         self.currency = currency<br>...     def __str__(self):<br>...         return f&#39;name: {self.name}, age: {self.age}, salary: {self.salary}{self.currency}&#39;<br>...     def __ge__(self, emp):<br>...         return self.salary &gt;= emp.salary<br>... </pre><p>This method gets invoked when the &gt;= operator is used and returns True or False.</p><pre>&gt;&gt;&gt; employee1 = Employee(&#39;employee x&#39;, 27, 200)<br>&gt;&gt;&gt; employee2 = Employee(&#39;employee y&#39;, 28, 300)<br>&gt;&gt;&gt; employee1 &gt;= employee2<br>False<br>&gt;&gt;&gt; employee2 &gt;= employee1<br>True</pre><h3>Finally</h3><p>you can use the appropriate magic methods to add various functionalities in your custom class. you can find out more magic methods listed in the <a href="https://docs.python.org/3/reference/datamodel.html#special-method-names">python documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e68452edb6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/anymind-group/magic-methods-dunder-in-python-1e68452edb6">[Tech Blog] Magic (“dunder”) Methods in Python</a> was originally published in <a href="https://medium.com/anymind-group">AnyMind Group</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>