# Python and Rego Language Comparison

Python is a versatile programming language commonly used in domains such as data analysis, web development, automation, and scientific computing. Python applications frequently interact with external data sources, handle sensitive information, and process unstructured and untrusted data.

Being so general-purpose Python can do all of these things, but expressing the related policies and rules can be error-prone and distract from the core logic of applications. This guide presents a series of examples illustrating how a policy can be expressed in Python and the corresponding Rego code for comparison.

## Check If a User Is an Admin

Admin status is often encoded in a [JWT](http://jwt.io) (JSON Web Token). This example shows how to extract information from a JWT and make an authorization decision based on it. The example uses an insecure secret to verify the JWT for brevity.

### Python

```
import jwt # pip install pyjwtdef allow(token):    try:        payload = jwt.decode(            token, "pa$$w0rd", algorithms=["HS256"])    except jwt.PyJWTError as e:        return False    if not "roles" in payload:        return False    return "admin" in payload["roles"]
```

### Rego

```
package exampleclaims := io.jwt.decode(input.token)[1] if {    io.jwt.verify_hs256(input.token, "pa$$w0rd")}default allow := falseallow if "admin" in claims.roles
```

**Note:** Verifying JWTs with a hard-coded secret is insecure and is used here for example only, please refer to the OPA documentation on [Token Verification](/docs/policy-reference/builtins/tokens) for more information on how to securely verify JWTs.

## Grant Access Based on Inherited Permissions

Staff roles are used to define permissions that a given user has within an organization. In this example, we show how permissions can be inherited from other roles based on the organization's staff hierarchy. Rego's [`graph.reachable`](https://www.openpolicyagent.org/docs/policy-reference/#builtin-graph-graphreachable) built-in function not only keeps the policy concise but is also safe from infinite recursion caused by cyclic dependencies in the staff hierarchy.

### Python

```
manages = {    "manager":   ["supervisor", "security"],    "supervisor": ["assistant"],    "assistant": [],    "security": [],}dataset_permissions = {    "manager": ["salaries"],    "supervisor": ["rotas"],    "security": ["cctv"],    "assistant": ["product_prices"],}def reachable_roles_for_role(role):    roles = [role]    for r in manages[role]:        roles.append(r)        roles.extend(reachable_roles_for_role(r))    return rolesdef allow(role, dataset):    inheritable_roles = reachable_roles_for_role(role)    for r in inheritable_roles:        if r in dataset_permissions:            if dataset in dataset_permissions[r]:                return True    return False
```

### Rego

```
package examplemanages := {    "manager": {"supervisor", "security"},    "supervisor": {"assistant"},    "security": set(),    "assistant": set(),}dataset_permissions := {    "manager": {"salaries"},    "supervisor": {"rotas"},    "security": {"cctv"},    "assistant": {"product_prices"},}default allow := falseallow if {    some inherited_role in graph.reachable(      manages, {input.role}    )    input.dataset in dataset_permissions[inherited_role]}
```

## Validate User-Generated Content

Policy is often used to guide users when they make mistakes. Validation of user-generated resources can be complicated and often needs to be implemented in many applications. This example compares code for validating a user-submitted blog post and shows how Rego rules can be defined [incrementally](/docs/policy-language/#incremental-definitions).

### Python

```
def validations(input):    messages = []    # ensure title and content are set    for field in ["title", "content"]:        if not input.get(field):            messages.append(f"Value missing for field '{field}'")    # ensure title starts with a capital letter    title = input.get("title", "")    if title and not title[0].isupper():        messages.append("Title must start with a capital")    # ensure user identifier is set    user = input.get("user", {})    if not user:        messages.append("User email or id must be set")    else:        if not any(k in user for k in ["email", "id"]):            messages.append("User email or id must be set")        # ensure example.com emails are not allowed        if user.get("email", "").endswith("@example.com"):            messages.append("example.com emails not allowed")    return messages
```

### Rego

```
package example# ensure title and content are setvalidations contains message if {    some field in {"title", "content"}    object.get(input, field, "") == ""    message := sprintf("Value missing for field '%s'", [field])}# ensure title starts with a capital lettervalidations contains "Title must start with a capital" if {    not regex.match(`^[A-Z]`, input.title)}# ensure user identifier is setvalidations contains "User email or id must be set" if {    not input.user.email    not input.user.id}# ensure example.com emails are not allowedvalidations contains "example.com emails not allowed" if {    endswith(input.user.email, "@example.com")}
```

![](/assets/images/java-6c64373d3b7415758078f77fcab4fbc0.png)

### Java

[Compare Java](/docs/comparisons/languages/java)

![](/assets/images/go-8a41c6e1bce5cfeabb5eaa0b1df1cda0.png)

### Go

[Compare Go](/docs/comparisons/languages/go)