pychd


Namepychd JSON
Version 0.1.6 PyPI version JSON
download
home_pagehttps://github.com/diohabara/pychd
SummaryThe ChatGPT-powered decompiler for Python, providing superior code analysis capabilities
upload_time2023-04-27 23:05:00
maintainer
docs_urlNone
author卍diohabara卍
requires_python>=3.8,<3.11
licenseMIT
keywords decompiler python poetry bytecode
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # PyChD

[![CI](https://github.com/diohabara/pychd/actions/workflows/ci.yml/badge.svg)](https://github.com/diohabara/pychd/actions/workflows/ci.yml)
[![PyPI Version](https://img.shields.io/pypi/v/pychd.svg)](https://pypi.python.org/pypi/pychd)

The ChatGPT-powered decompiler for Python, providing superior code analysis capabilities

## Usage

### Install

From pip

```bash
pip install pychd
```

### Compile

```bash
pychd compile <directory | file> # you need to specify a directory or a .py file
```

E.g.,

```bash
pychd compile examples/01_example_variables.py # `example/__pycache__/01_example_variables.cpython-310.pyc` will be created
```

### Decompile

```bash
pychd decompile <pyc-file> # you need to specify a .pyc file
```

E.g.,

```bash
pychd decompile example/__pycache__/01_example_variables.cpython-310.pyc # decompiled code will be printed
```

```bash
pychd decompile example/__pycache__/01_example_variables.cpython-310.pyc -o example/__pycache__/01_example_variables.cpython-310.py # decompiled code will be written to `example/__pycache__/01_example_variables.cpython-310.py`
```

## Examples

You can find examples in `example` directory or below (decompiled code is generated by `pychd` from Python-3.10-compiled `.pyc` code).

### Variables

original

```python
# Assigning values to variables
name = "John Doe"
age = 30
height = 6.1  # in feet

# Performing operations with variables
age_next_year = age + 1
half_height = height / 2

# Printing variables and their values
print("Name:", name)
print("Age:", age)
print("Height:", height, "feet")
print("Age next year:", age_next_year)
print("Half height:", half_height, "feet")

```

decompiled

```python
name = 'John Doe'
age = 30
height = 6.1
age_next_year = age + 1
half_height = height / 2

print('Name:', name)
print('Age:', age)
print('Height:', height, 'feet')
print('Age next year:', age_next_year)
print('Half height:', half_height, 'feet')
```

### Data types

original

```python
# Integer
integer_example = 42

# Float
float_example = 3.14

# String
string_example = "Hello, World!"

# List
list_example = [1, 2, 3, 4, 5]

# Tuple
tuple_example = (1, "apple", 3.14)

# Dictionary
dict_example = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

# Set
set_example = {1, 2, 3, 4, 5}

# Boolean
bool_example = True

# Printing the examples
print("Integer:", integer_example)
print("Float:", float_example)
print("String:", string_example)
print("List:", list_example)
print("Tuple:", tuple_example)
print("Dictionary:", dict_example)
print("Set:", set_example)
print("Boolean:", bool_example)

```

decompiled

```python
integer_example = 42
float_example = 3.14
string_example = 'Hello, World!'
list_example = [1, 2, 3, 4, 5]
tuple_example = (1, 'apple', 3.14)
dict_example = {'name': 'John Doe', 'age': 30, 'city': 'New York'}
set_example = {1, 2, 3, 4, 5}.union(frozenset({1, 2, 3, 4, 5}))
bool_example = True

print('Integer:', integer_example)
print('Float:', float_example)
print('String:', string_example)
print('List:', list_example)
print('Tuple:', tuple_example)
print('Dictionary:', dict_example)
print('Set:', set_example)
print('Boolean:', bool_example)
```

### Conditional statements (if-else)

original

```python
age = 25
country = "USA"
job_status = "employed"
favorite_color = "blue"

if age < 18 or (country == "USA" and favorite_color == "blue"):
    if job_status == "employed":
        print("Minor or USA + blue, employed.")
    elif job_status == "unemployed":
        print("Minor or USA + blue, unemployed.")
    else:
        print("Minor or USA + blue, other status.")
else:
    if job_status == "employed":
        if country != "USA" or favorite_color != "blue":
            print("Not minor, not USA + blue, employed.")
    elif job_status == "unemployed":
        if (country != "USA") ^ (favorite_color != "blue"):
            print("Not minor, not USA + blue, unemployed.")
    else:
        print("Not minor, not USA + blue, other status.")

```

decompiled

```python
age = 25
country = 'USA'
job_status = 'employed'
favorite_color = 'blue'

if age < 18 or (country == 'USA' and favorite_color == 'blue'):
    if job_status == 'employed':
        print('Minor or USA + blue, employed.')
    else:
        print('Minor or USA + blue, unemployed.')
else:
    if job_status == 'employed':
        if country != 'USA' or favorite_color != 'blue':
            print('Not minor, not USA + blue, employed.')
    else:
        if country != 'USA' or favorite_color != 'blue':
            print('Not minor, not USA + blue, unemployed.')
        else:
            print('Not minor, not USA + blue, other status.')
```

### Loops

original

```python
# Using a for loop to iterate through a list
fruits = ["apple", "banana", "orange", "grape"]
for fruit in fruits:
    print(f"Current fruit: {fruit}")

# Using a for loop with the range function
for i in range(5):
    print(f"Current value of i: {i}")

# Using a while loop
count = 0
while count < 5:
    print(f"Current count: {count}")
    count += 1

# Using a nested loop
for i in range(3):
    print(f"Outer loop, i: {i}")
    for j in range(2):
        print(f"  Inner loop, j: {j}")

```

decompiled

```python
fruits = ('apple', 'banana', 'orange', 'grape')
for fruit in fruits:
    print('Current fruit: {}'.format(fruit))
for i in range(5):
    print('Current value of i: {}'.format(i))
count = 0
while count < 5:
    print('Current count: {}'.format(count))
    count += 1
for i in range(3):
    print('Outer loop, i: {}'.format(i))
    for j in range(2):
        print('  Inner loop, j: {}'.format(j))
```

### List comprehensions

original

```python
# Basic list comprehension
squares = [x**2 for x in range(1, 6)]
print(squares)  # Output: [1, 4, 9, 16, 25]

# List comprehension with a condition
even_squares = [x**2 for x in range(1, 6) if x % 2 == 0]
print(even_squares)  # Output: [4, 16]

# Nested list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix))]
print(transpose)  # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

```

decompiled

```python
squares = [x**2 for x in range(1, 6)]
print(squares)

even_squares = [x**2 for x in range(1, 6) if x**2 % 2 == 0]
print(even_squares)

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix))]
print(transpose)
```

### Functions

original

```python
global_var = "I'm a global variable"

def outer_function():
    outer_local_var = "I'm a local variable in the outer function"

    def inner_function():
        nonlocal outer_local_var
        inner_local_var = "I'm a local variable in the inner function"
        print(f"Inner function: {inner_local_var}")
        print(f"Inner function: {outer_local_var}")
        print(f"Inner function: {global_var}")

    print(f"Outer function: {outer_local_var}")
    print(f"Outer function: {global_var}")

    inner_function()

def calculate(operation, a, b):
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        return a / b
    else:
        return None

# Test the outer_function
outer_function()

# Test the calculate function
print(calculate("add", 4, 5))

# Lambda function example
multiply = lambda x, y: x * y
print(multiply(3, 4))

```

decompiled

```python
global_var = "I'm a global variable"

def outer_function():
    outer_local_var = "I'm a local variable in the outer function"

    def inner_function():
        inner_local_var = "I'm a local variable in the inner function"
        print("Inner function: ", inner_local_var)
        print("Inner function: ", outer_local_var)
        print("Inner function: ", global_var)

    print("Outer function: ", outer_local_var)
    print("Outer function: ", global_var)
    inner_function()

def calculate(operation, a, b):
    if operation == 'add':
        return a + b
    elif operation == 'subtract':
        return a - b
    elif operation == 'multiply':
        return a * b
    elif operation == 'divide':
        return a / b
    else:
        return None

multiply = lambda x, y: x * y

print(calculate('add', 4, 5))
print(multiply(3, 4))
```

### Classes and objects

original

```python
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak(self):
        print(f"{self.name} makes a generic animal sound.")

    def describe(self):
        print(f"{self.name} is {self.age} years old.")


class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)
        self.breed = breed

    def speak(self):
        print(f"{self.name} barks!")

    def describe_breed(self):
        print(f"{self.name} is a {self.breed}.")


class Cat(Animal):
    def __init__(self, name, age, color):
        super().__init__(name, age)
        self.color = color

    def speak(self):
        print(f"{self.name} meows!")

    def describe_color(self):
        print(f"{self.name} has a {self.color} coat.")


# Creating objects
animal = Animal("Generic animal", 3)
dog = Dog("Buddy", 5, "Golden Retriever")
cat = Cat("Whiskers", 7, "black")

# Calling methods on objects
animal.speak()
animal.describe()

dog.speak()
dog.describe()
dog.describe_breed()

cat.speak()
cat.describe()
cat.describe_color()

```

decompiled

```python
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak(self):
        print(f"{self.name} makes a generic animal sound.")

    def describe(self):
        print(f"{self.name} is {self.age} years old.")


class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)
        self.breed = breed

    def speak(self):
        print(f"{self.name} barks!")

    def describe_breed(self):
        print(f"{self.name} is a {self.breed}.")


class Cat(Animal):
    def __init__(self, name, age, color):
        super().__init__(name, age)
        self.color = color

    def speak(self):
        print(f"{self.name} meows!")

    def describe_color(self):
        print(f"{self.name} has a {self.color} coat.")


animal = Animal("Generic animal", 3)
dog = Dog("Buddy", 5, "Golden Retriever")
cat = Cat("Whiskers", 7, "black")

animal.speak()
animal.describe()

dog.speak()
dog.describe()
dog.describe_breed()

cat.speak()
cat.describe()
cat.describe_color()
```

### Modules and packages

original

```python
from animals.mammals import get_mammals, get_mammal_info

def main():
    mammals = get_mammals()
    print("Mammals:")
    for mammal in mammals:
        print(mammal)

    print("\nMammal info:")
    for mammal in mammals:
        print(get_mammal_info(mammal))

if __name__ == "__main__":
    main()

```

decompiled

```python
from animals.mammals import get_mammals, get_mammal_info

def main():
    mammals = get_mammals()
    print('Mammals:')
    for mammal in mammals:
        print(mammal)
    print('\nMammal info:')
    for mammal in mammals:
        print(get_mammal_info(mammal))

if __name__ == '__main__':
    main()
```

### Exception handling

original

```python
def divide(a, b):
    try:
        result = a / b
        print(f"{a} divided by {b} is {result}")
    except ZeroDivisionError:
        print("Cannot divide by zero.")


divide(10, 2)
divide(10, 0)


def safe_conversion(value, to_int=True):
    try:
        if to_int:
            converted = int(value)
        else:
            converted = float(value)
        print(f"Converted {value} to {converted}")
    except ValueError:
        print(f"Invalid value: {value}")
    except TypeError:
        print(f"Unsupported type: {type(value).__name__}")


safe_conversion("42")
safe_conversion("3.14", False)
safe_conversion("abc")
safe_conversion(None)


def read_file(file_name):
    try:
        file = open(file_name, "r")
        content = file.read()
        print(f"File content:\n{content}")
    except FileNotFoundError:
        print("File not found.")
    finally:
        if "file" in locals() and not file.closed:
            file.close()
            print("File closed.")


read_file("example.txt")


class InvalidAgeError(ValueError):
    pass


def check_age(age):
    if age < 0:
        raise InvalidAgeError("Age cannot be negative.")
    elif age > 120:
        raise InvalidAgeError("Age is too high.")
    else:
        print("Age is valid.")


try:
    check_age(25)
    check_age(-5)
except InvalidAgeError as e:
    print(e)

```

decompiled

```python
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print('Cannot divide by zero.')
    else:
        print(f'{a} divided by {b} is {result}')

def safe_conversion(value, to_int=True):
    try:
        if to_int:
            converted = int(value)
        else:
            converted = float(value)
    except ValueError:
        print(f'Invalid value: {value}')
    except TypeError:
        print(f'Unsupported type: {type(value).__name__}')
    else:
        print(f'Converted {value} to {converted}')

def read_file(file_name):
    try:
        file = open(file_name, 'r')
    except FileNotFoundError:
        print('File not found.')
    else:
        content = file.read()
        print(f'File content:\n{content}')
        try:
            locals()['file']
        except KeyError:
            pass
        else:
            if not file.closed:
                file.close()
                print('File closed.')
            raise

class InvalidAgeError(ValueError):
    pass

def check_age(age):
    if age < 0:
        raise InvalidAgeError('Age cannot be negative.')
    elif age > 120:
        raise InvalidAgeError('Age is too high.')
    else:
        print('Age is valid.')
```

### File I/O

original

```python
file_name = "example.txt"

with open(file_name, "r") as file:
    content = file.read()
    print(f"File content:\n{content}")
file_name = "output.txt"
content = "Hello, World!"

with open(file_name, "w") as file:
    file.write(content)
    print(f"Wrote content to {file_name}")
file_name = "log.txt"
log_entry = "This is a log entry."

with open(file_name, "a") as file:
    file.write(f"{log_entry}\n")
    print(f"Appended log entry to {file_name}")
file_name = "example.txt"

with open(file_name, "r") as file:
    print(f"Reading {file_name} line by line:")
    for line in file:
        print(line.strip())
import json

file_name = "data.json"
data = {"name": "John", "age": 30, "city": "New York"}

# Writing JSON data to a file
with open(file_name, "w") as file:
    json.dump(data, file)
    print(f"Wrote JSON data to {file_name}")

# Reading JSON data from a file
with open(file_name, "r") as file:
    loaded_data = json.load(file)
    print(f"Read JSON data from {file_name}:")
    print(loaded_data)

```

decompiled

```python
file_name = 'example.txt'

with open(file_name, 'r') as file:
    content = file.read()

print('File content:\n{}'.format(content))

try:
    with open('output.txt', 'w') as file:
        content = 'Hello, World!'
        file.write(content)

    print('Wrote content to {}'.format(file_name))
except:
    pass

try:
    with open('log.txt', 'a') as file:
        log_entry = 'This is a log entry.'
        file.write('{}\n'.format(log_entry))

    print('Appended log entry to {}'.format(file_name))
except:
    pass

file_name = 'example.txt'

print('Reading {} line by line:'.format(file_name))
with open(file_name, 'r') as file:
    for line in file:
        print(line.strip())

import json

file_name = 'data.json'
data = {'name': 'John', 'age': 30, 'city': 'New York'}

with open(file_name, 'w') as file:
    json.dump(data, file)

print('Wrote JSON data to {}'.format(file_name))

with open(file_name, 'r') as file:
    loaded_data = json.load(file)

print('Read JSON data from {}:'.format(file_name))
print(loaded_data)
```

### Standard library

original

```python
import os

# Get the current working directory
cwd = os.getcwd()
print(f"Current working directory: {cwd}")

# List files and directories in the current directory
print("Files and directories in the current directory:")
for item in os.listdir(cwd):
    print(item)

# Create a new directory
new_dir = "example_directory"
os.makedirs(new_dir, exist_ok=True)
print(f"Created new directory: {new_dir}")

# Rename the directory
new_name = "renamed_directory"
os.rename(new_dir, new_name)
print(f"Renamed directory from {new_dir} to {new_name}")

# Remove the directory
os.rmdir(new_name)
print(f"Removed directory: {new_name}")
import shutil

src_file = "source.txt"
dst_file = "destination.txt"

# Copy a file
shutil.copy(src_file, dst_file)
print(f"Copied {src_file} to {dst_file}")

# Move a file
new_location = "moved.txt"
shutil.move(dst_file, new_location)
print(f"Moved {dst_file} to {new_location}")

# Remove a file
os.remove(new_location)
print(f"Removed file: {new_location}")
import glob

# Find all Python files in the current directory
print("Python files in the current directory:")
for py_file in glob.glob("*.py"):
    print(py_file)
import tempfile

# Create a temporary file and write content to it
with tempfile.NamedTemporaryFile(mode="w+t", delete=False) as temp_file:
    temp_file.write("Hello, World!")
    temp_path = temp_file.name
    print(f"Created temporary file: {temp_path}")

# Read the content of the temporary file
with open(temp_path, "r") as temp_file:
    content = temp_file.read()
    print(f"Content of the temporary file: {content}")

# Remove the temporary file
os.remove(temp_path)
print(f"Removed temporary file: {temp_path}")

```

decompiled

```python
import os
import shutil
import glob
import tempfile

cwd = os.getcwd()
print('Current working directory: {0}'.format(cwd))

print('Files and directories in the current directory:')
for item in os.listdir(cwd):
    print(item)

new_dir = 'example_directory'
os.makedirs(new_dir, exist_ok=True)
print('Created new directory: {0}'.format(new_dir))

new_name = 'renamed_directory'
os.rename(new_dir, new_name)
print('Renamed directory from {0} to {1}'.format(new_dir, new_name))

os.rmdir(new_name)
print('Removed directory: {0}'.format(new_name))

src_file = 'source.txt'
dst_file = 'destination.txt'
shutil.copy(src_file, dst_file)
print('Copied {0} to {1}'.format(src_file, dst_file))

new_location = 'moved.txt'
shutil.move(dst_file, new_location)
print('Moved {0} to {1}'.format(dst_file, new_location))

os.remove(new_location)
print('Removed file: {0}'.format(new_location))

print('Python files in the current directory:')
for py_file in glob.glob('*.py'):
    print(py_file)

with tempfile.NamedTemporaryFile('w+t', delete=False) as temp_file:
    temp_file.write('Hello, World!')
    temp_path = temp_file.name
    print('Created temporary file: {0}'.format(temp_path))

with open(temp_path, 'r') as temp_file:
    content = temp_file.read()
    print('Content of the temporary file: {0}'.format(content))

os.remove(temp_path)
print('Removed temporary file: {0}'.format(temp_path))
```

## Development

## Setup

```bash
poetry install
poetry run pre-commit install
```

Set `OPENAI_API_KEY` environment variable. If you're using `direnv`, you can use `.envrc.template` as a template.
Put `src/pychd/logging.conf`. You can copy `src/pychd/logging.conf.template` like this:

```bash
cp src/pychd/logging.conf.template src/pychd/logging.conf
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/diohabara/pychd",
    "name": "pychd",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<3.11",
    "maintainer_email": "",
    "keywords": "decompiler,python,poetry,bytecode",
    "author": "\u534ddiohabara\u534d",
    "author_email": "diohabara@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/4c/6f/7052a9185bfc81b55cf32c3c9f4e5457f2f208030fc36c57286d592d86e6/pychd-0.1.6.tar.gz",
    "platform": null,
    "description": "# PyChD\n\n[![CI](https://github.com/diohabara/pychd/actions/workflows/ci.yml/badge.svg)](https://github.com/diohabara/pychd/actions/workflows/ci.yml)\n[![PyPI Version](https://img.shields.io/pypi/v/pychd.svg)](https://pypi.python.org/pypi/pychd)\n\nThe ChatGPT-powered decompiler for Python, providing superior code analysis capabilities\n\n## Usage\n\n### Install\n\nFrom pip\n\n```bash\npip install pychd\n```\n\n### Compile\n\n```bash\npychd compile <directory | file> # you need to specify a directory or a .py file\n```\n\nE.g.,\n\n```bash\npychd compile examples/01_example_variables.py # `example/__pycache__/01_example_variables.cpython-310.pyc` will be created\n```\n\n### Decompile\n\n```bash\npychd decompile <pyc-file> # you need to specify a .pyc file\n```\n\nE.g.,\n\n```bash\npychd decompile example/__pycache__/01_example_variables.cpython-310.pyc # decompiled code will be printed\n```\n\n```bash\npychd decompile example/__pycache__/01_example_variables.cpython-310.pyc -o example/__pycache__/01_example_variables.cpython-310.py # decompiled code will be written to `example/__pycache__/01_example_variables.cpython-310.py`\n```\n\n## Examples\n\nYou can find examples in `example` directory or below (decompiled code is generated by `pychd` from Python-3.10-compiled `.pyc` code).\n\n### Variables\n\noriginal\n\n```python\n# Assigning values to variables\nname = \"John Doe\"\nage = 30\nheight = 6.1  # in feet\n\n# Performing operations with variables\nage_next_year = age + 1\nhalf_height = height / 2\n\n# Printing variables and their values\nprint(\"Name:\", name)\nprint(\"Age:\", age)\nprint(\"Height:\", height, \"feet\")\nprint(\"Age next year:\", age_next_year)\nprint(\"Half height:\", half_height, \"feet\")\n\n```\n\ndecompiled\n\n```python\nname = 'John Doe'\nage = 30\nheight = 6.1\nage_next_year = age + 1\nhalf_height = height / 2\n\nprint('Name:', name)\nprint('Age:', age)\nprint('Height:', height, 'feet')\nprint('Age next year:', age_next_year)\nprint('Half height:', half_height, 'feet')\n```\n\n### Data types\n\noriginal\n\n```python\n# Integer\ninteger_example = 42\n\n# Float\nfloat_example = 3.14\n\n# String\nstring_example = \"Hello, World!\"\n\n# List\nlist_example = [1, 2, 3, 4, 5]\n\n# Tuple\ntuple_example = (1, \"apple\", 3.14)\n\n# Dictionary\ndict_example = {\n    \"name\": \"John Doe\",\n    \"age\": 30,\n    \"city\": \"New York\"\n}\n\n# Set\nset_example = {1, 2, 3, 4, 5}\n\n# Boolean\nbool_example = True\n\n# Printing the examples\nprint(\"Integer:\", integer_example)\nprint(\"Float:\", float_example)\nprint(\"String:\", string_example)\nprint(\"List:\", list_example)\nprint(\"Tuple:\", tuple_example)\nprint(\"Dictionary:\", dict_example)\nprint(\"Set:\", set_example)\nprint(\"Boolean:\", bool_example)\n\n```\n\ndecompiled\n\n```python\ninteger_example = 42\nfloat_example = 3.14\nstring_example = 'Hello, World!'\nlist_example = [1, 2, 3, 4, 5]\ntuple_example = (1, 'apple', 3.14)\ndict_example = {'name': 'John Doe', 'age': 30, 'city': 'New York'}\nset_example = {1, 2, 3, 4, 5}.union(frozenset({1, 2, 3, 4, 5}))\nbool_example = True\n\nprint('Integer:', integer_example)\nprint('Float:', float_example)\nprint('String:', string_example)\nprint('List:', list_example)\nprint('Tuple:', tuple_example)\nprint('Dictionary:', dict_example)\nprint('Set:', set_example)\nprint('Boolean:', bool_example)\n```\n\n### Conditional statements (if-else)\n\noriginal\n\n```python\nage = 25\ncountry = \"USA\"\njob_status = \"employed\"\nfavorite_color = \"blue\"\n\nif age < 18 or (country == \"USA\" and favorite_color == \"blue\"):\n    if job_status == \"employed\":\n        print(\"Minor or USA + blue, employed.\")\n    elif job_status == \"unemployed\":\n        print(\"Minor or USA + blue, unemployed.\")\n    else:\n        print(\"Minor or USA + blue, other status.\")\nelse:\n    if job_status == \"employed\":\n        if country != \"USA\" or favorite_color != \"blue\":\n            print(\"Not minor, not USA + blue, employed.\")\n    elif job_status == \"unemployed\":\n        if (country != \"USA\") ^ (favorite_color != \"blue\"):\n            print(\"Not minor, not USA + blue, unemployed.\")\n    else:\n        print(\"Not minor, not USA + blue, other status.\")\n\n```\n\ndecompiled\n\n```python\nage = 25\ncountry = 'USA'\njob_status = 'employed'\nfavorite_color = 'blue'\n\nif age < 18 or (country == 'USA' and favorite_color == 'blue'):\n    if job_status == 'employed':\n        print('Minor or USA + blue, employed.')\n    else:\n        print('Minor or USA + blue, unemployed.')\nelse:\n    if job_status == 'employed':\n        if country != 'USA' or favorite_color != 'blue':\n            print('Not minor, not USA + blue, employed.')\n    else:\n        if country != 'USA' or favorite_color != 'blue':\n            print('Not minor, not USA + blue, unemployed.')\n        else:\n            print('Not minor, not USA + blue, other status.')\n```\n\n### Loops\n\noriginal\n\n```python\n# Using a for loop to iterate through a list\nfruits = [\"apple\", \"banana\", \"orange\", \"grape\"]\nfor fruit in fruits:\n    print(f\"Current fruit: {fruit}\")\n\n# Using a for loop with the range function\nfor i in range(5):\n    print(f\"Current value of i: {i}\")\n\n# Using a while loop\ncount = 0\nwhile count < 5:\n    print(f\"Current count: {count}\")\n    count += 1\n\n# Using a nested loop\nfor i in range(3):\n    print(f\"Outer loop, i: {i}\")\n    for j in range(2):\n        print(f\"  Inner loop, j: {j}\")\n\n```\n\ndecompiled\n\n```python\nfruits = ('apple', 'banana', 'orange', 'grape')\nfor fruit in fruits:\n    print('Current fruit: {}'.format(fruit))\nfor i in range(5):\n    print('Current value of i: {}'.format(i))\ncount = 0\nwhile count < 5:\n    print('Current count: {}'.format(count))\n    count += 1\nfor i in range(3):\n    print('Outer loop, i: {}'.format(i))\n    for j in range(2):\n        print('  Inner loop, j: {}'.format(j))\n```\n\n### List comprehensions\n\noriginal\n\n```python\n# Basic list comprehension\nsquares = [x**2 for x in range(1, 6)]\nprint(squares)  # Output: [1, 4, 9, 16, 25]\n\n# List comprehension with a condition\neven_squares = [x**2 for x in range(1, 6) if x % 2 == 0]\nprint(even_squares)  # Output: [4, 16]\n\n# Nested list comprehension\nmatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\ntranspose = [[row[i] for row in matrix] for i in range(len(matrix))]\nprint(transpose)  # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n\n```\n\ndecompiled\n\n```python\nsquares = [x**2 for x in range(1, 6)]\nprint(squares)\n\neven_squares = [x**2 for x in range(1, 6) if x**2 % 2 == 0]\nprint(even_squares)\n\nmatrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\ntranspose = [[row[i] for row in matrix] for i in range(len(matrix))]\nprint(transpose)\n```\n\n### Functions\n\noriginal\n\n```python\nglobal_var = \"I'm a global variable\"\n\ndef outer_function():\n    outer_local_var = \"I'm a local variable in the outer function\"\n\n    def inner_function():\n        nonlocal outer_local_var\n        inner_local_var = \"I'm a local variable in the inner function\"\n        print(f\"Inner function: {inner_local_var}\")\n        print(f\"Inner function: {outer_local_var}\")\n        print(f\"Inner function: {global_var}\")\n\n    print(f\"Outer function: {outer_local_var}\")\n    print(f\"Outer function: {global_var}\")\n\n    inner_function()\n\ndef calculate(operation, a, b):\n    if operation == \"add\":\n        return a + b\n    elif operation == \"subtract\":\n        return a - b\n    elif operation == \"multiply\":\n        return a * b\n    elif operation == \"divide\":\n        return a / b\n    else:\n        return None\n\n# Test the outer_function\nouter_function()\n\n# Test the calculate function\nprint(calculate(\"add\", 4, 5))\n\n# Lambda function example\nmultiply = lambda x, y: x * y\nprint(multiply(3, 4))\n\n```\n\ndecompiled\n\n```python\nglobal_var = \"I'm a global variable\"\n\ndef outer_function():\n    outer_local_var = \"I'm a local variable in the outer function\"\n\n    def inner_function():\n        inner_local_var = \"I'm a local variable in the inner function\"\n        print(\"Inner function: \", inner_local_var)\n        print(\"Inner function: \", outer_local_var)\n        print(\"Inner function: \", global_var)\n\n    print(\"Outer function: \", outer_local_var)\n    print(\"Outer function: \", global_var)\n    inner_function()\n\ndef calculate(operation, a, b):\n    if operation == 'add':\n        return a + b\n    elif operation == 'subtract':\n        return a - b\n    elif operation == 'multiply':\n        return a * b\n    elif operation == 'divide':\n        return a / b\n    else:\n        return None\n\nmultiply = lambda x, y: x * y\n\nprint(calculate('add', 4, 5))\nprint(multiply(3, 4))\n```\n\n### Classes and objects\n\noriginal\n\n```python\nclass Animal:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n\n    def speak(self):\n        print(f\"{self.name} makes a generic animal sound.\")\n\n    def describe(self):\n        print(f\"{self.name} is {self.age} years old.\")\n\n\nclass Dog(Animal):\n    def __init__(self, name, age, breed):\n        super().__init__(name, age)\n        self.breed = breed\n\n    def speak(self):\n        print(f\"{self.name} barks!\")\n\n    def describe_breed(self):\n        print(f\"{self.name} is a {self.breed}.\")\n\n\nclass Cat(Animal):\n    def __init__(self, name, age, color):\n        super().__init__(name, age)\n        self.color = color\n\n    def speak(self):\n        print(f\"{self.name} meows!\")\n\n    def describe_color(self):\n        print(f\"{self.name} has a {self.color} coat.\")\n\n\n# Creating objects\nanimal = Animal(\"Generic animal\", 3)\ndog = Dog(\"Buddy\", 5, \"Golden Retriever\")\ncat = Cat(\"Whiskers\", 7, \"black\")\n\n# Calling methods on objects\nanimal.speak()\nanimal.describe()\n\ndog.speak()\ndog.describe()\ndog.describe_breed()\n\ncat.speak()\ncat.describe()\ncat.describe_color()\n\n```\n\ndecompiled\n\n```python\nclass Animal:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n\n    def speak(self):\n        print(f\"{self.name} makes a generic animal sound.\")\n\n    def describe(self):\n        print(f\"{self.name} is {self.age} years old.\")\n\n\nclass Dog(Animal):\n    def __init__(self, name, age, breed):\n        super().__init__(name, age)\n        self.breed = breed\n\n    def speak(self):\n        print(f\"{self.name} barks!\")\n\n    def describe_breed(self):\n        print(f\"{self.name} is a {self.breed}.\")\n\n\nclass Cat(Animal):\n    def __init__(self, name, age, color):\n        super().__init__(name, age)\n        self.color = color\n\n    def speak(self):\n        print(f\"{self.name} meows!\")\n\n    def describe_color(self):\n        print(f\"{self.name} has a {self.color} coat.\")\n\n\nanimal = Animal(\"Generic animal\", 3)\ndog = Dog(\"Buddy\", 5, \"Golden Retriever\")\ncat = Cat(\"Whiskers\", 7, \"black\")\n\nanimal.speak()\nanimal.describe()\n\ndog.speak()\ndog.describe()\ndog.describe_breed()\n\ncat.speak()\ncat.describe()\ncat.describe_color()\n```\n\n### Modules and packages\n\noriginal\n\n```python\nfrom animals.mammals import get_mammals, get_mammal_info\n\ndef main():\n    mammals = get_mammals()\n    print(\"Mammals:\")\n    for mammal in mammals:\n        print(mammal)\n\n    print(\"\\nMammal info:\")\n    for mammal in mammals:\n        print(get_mammal_info(mammal))\n\nif __name__ == \"__main__\":\n    main()\n\n```\n\ndecompiled\n\n```python\nfrom animals.mammals import get_mammals, get_mammal_info\n\ndef main():\n    mammals = get_mammals()\n    print('Mammals:')\n    for mammal in mammals:\n        print(mammal)\n    print('\\nMammal info:')\n    for mammal in mammals:\n        print(get_mammal_info(mammal))\n\nif __name__ == '__main__':\n    main()\n```\n\n### Exception handling\n\noriginal\n\n```python\ndef divide(a, b):\n    try:\n        result = a / b\n        print(f\"{a} divided by {b} is {result}\")\n    except ZeroDivisionError:\n        print(\"Cannot divide by zero.\")\n\n\ndivide(10, 2)\ndivide(10, 0)\n\n\ndef safe_conversion(value, to_int=True):\n    try:\n        if to_int:\n            converted = int(value)\n        else:\n            converted = float(value)\n        print(f\"Converted {value} to {converted}\")\n    except ValueError:\n        print(f\"Invalid value: {value}\")\n    except TypeError:\n        print(f\"Unsupported type: {type(value).__name__}\")\n\n\nsafe_conversion(\"42\")\nsafe_conversion(\"3.14\", False)\nsafe_conversion(\"abc\")\nsafe_conversion(None)\n\n\ndef read_file(file_name):\n    try:\n        file = open(file_name, \"r\")\n        content = file.read()\n        print(f\"File content:\\n{content}\")\n    except FileNotFoundError:\n        print(\"File not found.\")\n    finally:\n        if \"file\" in locals() and not file.closed:\n            file.close()\n            print(\"File closed.\")\n\n\nread_file(\"example.txt\")\n\n\nclass InvalidAgeError(ValueError):\n    pass\n\n\ndef check_age(age):\n    if age < 0:\n        raise InvalidAgeError(\"Age cannot be negative.\")\n    elif age > 120:\n        raise InvalidAgeError(\"Age is too high.\")\n    else:\n        print(\"Age is valid.\")\n\n\ntry:\n    check_age(25)\n    check_age(-5)\nexcept InvalidAgeError as e:\n    print(e)\n\n```\n\ndecompiled\n\n```python\ndef divide(a, b):\n    try:\n        result = a / b\n    except ZeroDivisionError:\n        print('Cannot divide by zero.')\n    else:\n        print(f'{a} divided by {b} is {result}')\n\ndef safe_conversion(value, to_int=True):\n    try:\n        if to_int:\n            converted = int(value)\n        else:\n            converted = float(value)\n    except ValueError:\n        print(f'Invalid value: {value}')\n    except TypeError:\n        print(f'Unsupported type: {type(value).__name__}')\n    else:\n        print(f'Converted {value} to {converted}')\n\ndef read_file(file_name):\n    try:\n        file = open(file_name, 'r')\n    except FileNotFoundError:\n        print('File not found.')\n    else:\n        content = file.read()\n        print(f'File content:\\n{content}')\n        try:\n            locals()['file']\n        except KeyError:\n            pass\n        else:\n            if not file.closed:\n                file.close()\n                print('File closed.')\n            raise\n\nclass InvalidAgeError(ValueError):\n    pass\n\ndef check_age(age):\n    if age < 0:\n        raise InvalidAgeError('Age cannot be negative.')\n    elif age > 120:\n        raise InvalidAgeError('Age is too high.')\n    else:\n        print('Age is valid.')\n```\n\n### File I/O\n\noriginal\n\n```python\nfile_name = \"example.txt\"\n\nwith open(file_name, \"r\") as file:\n    content = file.read()\n    print(f\"File content:\\n{content}\")\nfile_name = \"output.txt\"\ncontent = \"Hello, World!\"\n\nwith open(file_name, \"w\") as file:\n    file.write(content)\n    print(f\"Wrote content to {file_name}\")\nfile_name = \"log.txt\"\nlog_entry = \"This is a log entry.\"\n\nwith open(file_name, \"a\") as file:\n    file.write(f\"{log_entry}\\n\")\n    print(f\"Appended log entry to {file_name}\")\nfile_name = \"example.txt\"\n\nwith open(file_name, \"r\") as file:\n    print(f\"Reading {file_name} line by line:\")\n    for line in file:\n        print(line.strip())\nimport json\n\nfile_name = \"data.json\"\ndata = {\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}\n\n# Writing JSON data to a file\nwith open(file_name, \"w\") as file:\n    json.dump(data, file)\n    print(f\"Wrote JSON data to {file_name}\")\n\n# Reading JSON data from a file\nwith open(file_name, \"r\") as file:\n    loaded_data = json.load(file)\n    print(f\"Read JSON data from {file_name}:\")\n    print(loaded_data)\n\n```\n\ndecompiled\n\n```python\nfile_name = 'example.txt'\n\nwith open(file_name, 'r') as file:\n    content = file.read()\n\nprint('File content:\\n{}'.format(content))\n\ntry:\n    with open('output.txt', 'w') as file:\n        content = 'Hello, World!'\n        file.write(content)\n\n    print('Wrote content to {}'.format(file_name))\nexcept:\n    pass\n\ntry:\n    with open('log.txt', 'a') as file:\n        log_entry = 'This is a log entry.'\n        file.write('{}\\n'.format(log_entry))\n\n    print('Appended log entry to {}'.format(file_name))\nexcept:\n    pass\n\nfile_name = 'example.txt'\n\nprint('Reading {} line by line:'.format(file_name))\nwith open(file_name, 'r') as file:\n    for line in file:\n        print(line.strip())\n\nimport json\n\nfile_name = 'data.json'\ndata = {'name': 'John', 'age': 30, 'city': 'New York'}\n\nwith open(file_name, 'w') as file:\n    json.dump(data, file)\n\nprint('Wrote JSON data to {}'.format(file_name))\n\nwith open(file_name, 'r') as file:\n    loaded_data = json.load(file)\n\nprint('Read JSON data from {}:'.format(file_name))\nprint(loaded_data)\n```\n\n### Standard library\n\noriginal\n\n```python\nimport os\n\n# Get the current working directory\ncwd = os.getcwd()\nprint(f\"Current working directory: {cwd}\")\n\n# List files and directories in the current directory\nprint(\"Files and directories in the current directory:\")\nfor item in os.listdir(cwd):\n    print(item)\n\n# Create a new directory\nnew_dir = \"example_directory\"\nos.makedirs(new_dir, exist_ok=True)\nprint(f\"Created new directory: {new_dir}\")\n\n# Rename the directory\nnew_name = \"renamed_directory\"\nos.rename(new_dir, new_name)\nprint(f\"Renamed directory from {new_dir} to {new_name}\")\n\n# Remove the directory\nos.rmdir(new_name)\nprint(f\"Removed directory: {new_name}\")\nimport shutil\n\nsrc_file = \"source.txt\"\ndst_file = \"destination.txt\"\n\n# Copy a file\nshutil.copy(src_file, dst_file)\nprint(f\"Copied {src_file} to {dst_file}\")\n\n# Move a file\nnew_location = \"moved.txt\"\nshutil.move(dst_file, new_location)\nprint(f\"Moved {dst_file} to {new_location}\")\n\n# Remove a file\nos.remove(new_location)\nprint(f\"Removed file: {new_location}\")\nimport glob\n\n# Find all Python files in the current directory\nprint(\"Python files in the current directory:\")\nfor py_file in glob.glob(\"*.py\"):\n    print(py_file)\nimport tempfile\n\n# Create a temporary file and write content to it\nwith tempfile.NamedTemporaryFile(mode=\"w+t\", delete=False) as temp_file:\n    temp_file.write(\"Hello, World!\")\n    temp_path = temp_file.name\n    print(f\"Created temporary file: {temp_path}\")\n\n# Read the content of the temporary file\nwith open(temp_path, \"r\") as temp_file:\n    content = temp_file.read()\n    print(f\"Content of the temporary file: {content}\")\n\n# Remove the temporary file\nos.remove(temp_path)\nprint(f\"Removed temporary file: {temp_path}\")\n\n```\n\ndecompiled\n\n```python\nimport os\nimport shutil\nimport glob\nimport tempfile\n\ncwd = os.getcwd()\nprint('Current working directory: {0}'.format(cwd))\n\nprint('Files and directories in the current directory:')\nfor item in os.listdir(cwd):\n    print(item)\n\nnew_dir = 'example_directory'\nos.makedirs(new_dir, exist_ok=True)\nprint('Created new directory: {0}'.format(new_dir))\n\nnew_name = 'renamed_directory'\nos.rename(new_dir, new_name)\nprint('Renamed directory from {0} to {1}'.format(new_dir, new_name))\n\nos.rmdir(new_name)\nprint('Removed directory: {0}'.format(new_name))\n\nsrc_file = 'source.txt'\ndst_file = 'destination.txt'\nshutil.copy(src_file, dst_file)\nprint('Copied {0} to {1}'.format(src_file, dst_file))\n\nnew_location = 'moved.txt'\nshutil.move(dst_file, new_location)\nprint('Moved {0} to {1}'.format(dst_file, new_location))\n\nos.remove(new_location)\nprint('Removed file: {0}'.format(new_location))\n\nprint('Python files in the current directory:')\nfor py_file in glob.glob('*.py'):\n    print(py_file)\n\nwith tempfile.NamedTemporaryFile('w+t', delete=False) as temp_file:\n    temp_file.write('Hello, World!')\n    temp_path = temp_file.name\n    print('Created temporary file: {0}'.format(temp_path))\n\nwith open(temp_path, 'r') as temp_file:\n    content = temp_file.read()\n    print('Content of the temporary file: {0}'.format(content))\n\nos.remove(temp_path)\nprint('Removed temporary file: {0}'.format(temp_path))\n```\n\n## Development\n\n## Setup\n\n```bash\npoetry install\npoetry run pre-commit install\n```\n\nSet `OPENAI_API_KEY` environment variable. If you're using `direnv`, you can use `.envrc.template` as a template.\nPut `src/pychd/logging.conf`. You can copy `src/pychd/logging.conf.template` like this:\n\n```bash\ncp src/pychd/logging.conf.template src/pychd/logging.conf\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "The ChatGPT-powered decompiler for Python, providing superior code analysis capabilities",
    "version": "0.1.6",
    "split_keywords": [
        "decompiler",
        "python",
        "poetry",
        "bytecode"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "748492a209d3b3b7996f8bc157bbb2c0f5dffa10a5e41d99d49d71db7c30c176",
                "md5": "d713582978dee0abf040fc2b5bfeb1c0",
                "sha256": "c78cd4ebed8821e5556129ab8ed743b5cec5d5506f35aa58b0c248eb70a53282"
            },
            "downloads": -1,
            "filename": "pychd-0.1.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d713582978dee0abf040fc2b5bfeb1c0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<3.11",
            "size": 9674,
            "upload_time": "2023-04-27T23:04:59",
            "upload_time_iso_8601": "2023-04-27T23:04:59.327263Z",
            "url": "https://files.pythonhosted.org/packages/74/84/92a209d3b3b7996f8bc157bbb2c0f5dffa10a5e41d99d49d71db7c30c176/pychd-0.1.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4c6f7052a9185bfc81b55cf32c3c9f4e5457f2f208030fc36c57286d592d86e6",
                "md5": "c039ec405dc951437042870722bb0a30",
                "sha256": "e8af3d72717931169625308e26e2292b65116be0494e222c13a90df56224d2e1"
            },
            "downloads": -1,
            "filename": "pychd-0.1.6.tar.gz",
            "has_sig": false,
            "md5_digest": "c039ec405dc951437042870722bb0a30",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<3.11",
            "size": 12551,
            "upload_time": "2023-04-27T23:05:00",
            "upload_time_iso_8601": "2023-04-27T23:05:00.958010Z",
            "url": "https://files.pythonhosted.org/packages/4c/6f/7052a9185bfc81b55cf32c3c9f4e5457f2f208030fc36c57286d592d86e6/pychd-0.1.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-04-27 23:05:00",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "diohabara",
    "github_project": "pychd",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pychd"
}
        
Elapsed time: 0.05920s