Package: pychd
PyChDThe ChatGPT-powered decompiler for Python, providing superior code analysis capabilitiesUsageInstallFrom pippipinstallpychdCompilepychdcompile<directory|file># you need to specify a directory or a .py fileE.g.,pychdcompileexamples/01_example_variables.py# `example/__pycache__/01_example_variables.cpython-310.pyc` will be createdDecompilepychddecompile<pyc-file># you need to specify a .pyc fileE.g.,pychddecompileexample/__pycache__/01_example_variables.cpython-310.pyc# decompiled code will be printedpychddecompileexample/__pycache__/01_example_variables.cpython-310.pyc-oexample/__pycache__/01_example_variables.cpython-310.py# decompiled code will be written to `example/__pycache__/01_example_variables.cpython-310.py`ExamplesYou can find examples inexampledirectory or below (decompiled code is generated bypychdfrom Python-3.10-compiled.pyccode).Variablesoriginal# Assigning values to variablesname="John Doe"age=30height=6.1# in feet# Performing operations with variablesage_next_year=age+1half_height=height/2# Printing variables and their valuesprint("Name:",name)print("Age:",age)print("Height:",height,"feet")print("Age next year:",age_next_year)print("Half height:",half_height,"feet")decompiledname='John Doe'age=30height=6.1age_next_year=age+1half_height=height/2print('Name:',name)print('Age:',age)print('Height:',height,'feet')print('Age next year:',age_next_year)print('Half height:',half_height,'feet')Data typesoriginal# Integerinteger_example=42# Floatfloat_example=3.14# Stringstring_example="Hello, World!"# Listlist_example=[1,2,3,4,5]# Tupletuple_example=(1,"apple",3.14)# Dictionarydict_example={"name":"John Doe","age":30,"city":"New York"}# Setset_example={1,2,3,4,5}# Booleanbool_example=True# Printing the examplesprint("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)decompiledinteger_example=42float_example=3.14string_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=Trueprint('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)originalage=25country="USA"job_status="employed"favorite_color="blue"ifage<18or(country=="USA"andfavorite_color=="blue"):ifjob_status=="employed":print("Minor or USA + blue, employed.")elifjob_status=="unemployed":print("Minor or USA + blue, unemployed.")else:print("Minor or USA + blue, other status.")else:ifjob_status=="employed":ifcountry!="USA"orfavorite_color!="blue":print("Not minor, not USA + blue, employed.")elifjob_status=="unemployed":if(country!="USA")^(favorite_color!="blue"):print("Not minor, not USA + blue, unemployed.")else:print("Not minor, not USA + blue, other status.")decompiledage=25country='USA'job_status='employed'favorite_color='blue'ifage<18or(country=='USA'andfavorite_color=='blue'):ifjob_status=='employed':print('Minor or USA + blue, employed.')else:print('Minor or USA + blue, unemployed.')else:ifjob_status=='employed':ifcountry!='USA'orfavorite_color!='blue':print('Not minor, not USA + blue, employed.')else:ifcountry!='USA'orfavorite_color!='blue':print('Not minor, not USA + blue, unemployed.')else:print('Not minor, not USA + blue, other status.')Loopsoriginal# Using a for loop to iterate through a listfruits=["apple","banana","orange","grape"]forfruitinfruits:print(f"Current fruit:{fruit}")# Using a for loop with the range functionforiinrange(5):print(f"Current value of i:{i}")# Using a while loopcount=0whilecount<5:print(f"Current count:{count}")count+=1# Using a nested loopforiinrange(3):print(f"Outer loop, i:{i}")forjinrange(2):print(f"  Inner loop, j:{j}")decompiledfruits=('apple','banana','orange','grape')forfruitinfruits:print('Current fruit:{}'.format(fruit))foriinrange(5):print('Current value of i:{}'.format(i))count=0whilecount<5:print('Current count:{}'.format(count))count+=1foriinrange(3):print('Outer loop, i:{}'.format(i))forjinrange(2):print('  Inner loop, j:{}'.format(j))List comprehensionsoriginal# Basic list comprehensionsquares=[x**2forxinrange(1,6)]print(squares)# Output: [1, 4, 9, 16, 25]# List comprehension with a conditioneven_squares=[x**2forxinrange(1,6)ifx%2==0]print(even_squares)# Output: [4, 16]# Nested list comprehensionmatrix=[[1,2,3],[4,5,6],[7,8,9]]transpose=[[row[i]forrowinmatrix]foriinrange(len(matrix))]print(transpose)# Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]decompiledsquares=[x**2forxinrange(1,6)]print(squares)even_squares=[x**2forxinrange(1,6)ifx**2%2==0]print(even_squares)matrix=[[1,2,3],[4,5,6],[7,8,9]]transpose=[[row[i]forrowinmatrix]foriinrange(len(matrix))]print(transpose)Functionsoriginalglobal_var="I'm a global variable"defouter_function():outer_local_var="I'm a local variable in the outer function"definner_function():nonlocalouter_local_varinner_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()defcalculate(operation,a,b):ifoperation=="add":returna+belifoperation=="subtract":returna-belifoperation=="multiply":returna*belifoperation=="divide":returna/belse:returnNone# Test the outer_functionouter_function()# Test the calculate functionprint(calculate("add",4,5))# Lambda function examplemultiply=lambdax,y:x*yprint(multiply(3,4))decompiledglobal_var="I'm a global variable"defouter_function():outer_local_var="I'm a local variable in the outer function"definner_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()defcalculate(operation,a,b):ifoperation=='add':returna+belifoperation=='subtract':returna-belifoperation=='multiply':returna*belifoperation=='divide':returna/belse:returnNonemultiply=lambdax,y:x*yprint(calculate('add',4,5))print(multiply(3,4))Classes and objectsoriginalclassAnimal:def__init__(self,name,age):self.name=nameself.age=agedefspeak(self):print(f"{self.name}makes a generic animal sound.")defdescribe(self):print(f"{self.name}is{self.age}years old.")classDog(Animal):def__init__(self,name,age,breed):super().__init__(name,age)self.breed=breeddefspeak(self):print(f"{self.name}barks!")defdescribe_breed(self):print(f"{self.name}is a{self.breed}.")classCat(Animal):def__init__(self,name,age,color):super().__init__(name,age)self.color=colordefspeak(self):print(f"{self.name}meows!")defdescribe_color(self):print(f"{self.name}has a{self.color}coat.")# Creating objectsanimal=Animal("Generic animal",3)dog=Dog("Buddy",5,"Golden Retriever")cat=Cat("Whiskers",7,"black")# Calling methods on objectsanimal.speak()animal.describe()dog.speak()dog.describe()dog.describe_breed()cat.speak()cat.describe()cat.describe_color()decompiledclassAnimal:def__init__(self,name,age):self.name=nameself.age=agedefspeak(self):print(f"{self.name}makes a generic animal sound.")defdescribe(self):print(f"{self.name}is{self.age}years old.")classDog(Animal):def__init__(self,name,age,breed):super().__init__(name,age)self.breed=breeddefspeak(self):print(f"{self.name}barks!")defdescribe_breed(self):print(f"{self.name}is a{self.breed}.")classCat(Animal):def__init__(self,name,age,color):super().__init__(name,age)self.color=colordefspeak(self):print(f"{self.name}meows!")defdescribe_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 packagesoriginalfromanimals.mammalsimportget_mammals,get_mammal_infodefmain():mammals=get_mammals()print("Mammals:")formammalinmammals:print(mammal)print("\nMammal info:")formammalinmammals:print(get_mammal_info(mammal))if__name__=="__main__":main()decompiledfromanimals.mammalsimportget_mammals,get_mammal_infodefmain():mammals=get_mammals()print('Mammals:')formammalinmammals:print(mammal)print('\nMammal info:')formammalinmammals:print(get_mammal_info(mammal))if__name__=='__main__':main()Exception handlingoriginaldefdivide(a,b):try:result=a/bprint(f"{a}divided by{b}is{result}")exceptZeroDivisionError:print("Cannot divide by zero.")divide(10,2)divide(10,0)defsafe_conversion(value,to_int=True):try:ifto_int:converted=int(value)else:converted=float(value)print(f"Converted{value}to{converted}")exceptValueError:print(f"Invalid value:{value}")exceptTypeError:print(f"Unsupported type:{type(value).__name__}")safe_conversion("42")safe_conversion("3.14",False)safe_conversion("abc")safe_conversion(None)defread_file(file_name):try:file=open(file_name,"r")content=file.read()print(f"File content:\n{content}")exceptFileNotFoundError:print("File not found.")finally:if"file"inlocals()andnotfile.closed:file.close()print("File closed.")read_file("example.txt")classInvalidAgeError(ValueError):passdefcheck_age(age):ifage<0:raiseInvalidAgeError("Age cannot be negative.")elifage>120:raiseInvalidAgeError("Age is too high.")else:print("Age is valid.")try:check_age(25)check_age(-5)exceptInvalidAgeErrorase:print(e)decompileddefdivide(a,b):try:result=a/bexceptZeroDivisionError:print('Cannot divide by zero.')else:print(f'{a}divided by{b}is{result}')defsafe_conversion(value,to_int=True):try:ifto_int:converted=int(value)else:converted=float(value)exceptValueError:print(f'Invalid value:{value}')exceptTypeError:print(f'Unsupported type:{type(value).__name__}')else:print(f'Converted{value}to{converted}')defread_file(file_name):try:file=open(file_name,'r')exceptFileNotFoundError:print('File not found.')else:content=file.read()print(f'File content:\n{content}')try:locals()['file']exceptKeyError:passelse:ifnotfile.closed:file.close()print('File closed.')raiseclassInvalidAgeError(ValueError):passdefcheck_age(age):ifage<0:raiseInvalidAgeError('Age cannot be negative.')elifage>120:raiseInvalidAgeError('Age is too high.')else:print('Age is valid.')File I/Ooriginalfile_name="example.txt"withopen(file_name,"r")asfile:content=file.read()print(f"File content:\n{content}")file_name="output.txt"content="Hello, World!"withopen(file_name,"w")asfile:file.write(content)print(f"Wrote content to{file_name}")file_name="log.txt"log_entry="This is a log entry."withopen(file_name,"a")asfile:file.write(f"{log_entry}\n")print(f"Appended log entry to{file_name}")file_name="example.txt"withopen(file_name,"r")asfile:print(f"Reading{file_name}line by line:")forlineinfile:print(line.strip())importjsonfile_name="data.json"data={"name":"John","age":30,"city":"New York"}# Writing JSON data to a filewithopen(file_name,"w")asfile:json.dump(data,file)print(f"Wrote JSON data to{file_name}")# Reading JSON data from a filewithopen(file_name,"r")asfile:loaded_data=json.load(file)print(f"Read JSON data from{file_name}:")print(loaded_data)decompiledfile_name='example.txt'withopen(file_name,'r')asfile:content=file.read()print('File content:\n{}'.format(content))try:withopen('output.txt','w')asfile:content='Hello, World!'file.write(content)print('Wrote content to{}'.format(file_name))except:passtry:withopen('log.txt','a')asfile:log_entry='This is a log entry.'file.write('{}\n'.format(log_entry))print('Appended log entry to{}'.format(file_name))except:passfile_name='example.txt'print('Reading{}line by line:'.format(file_name))withopen(file_name,'r')asfile:forlineinfile:print(line.strip())importjsonfile_name='data.json'data={'name':'John','age':30,'city':'New York'}withopen(file_name,'w')asfile:json.dump(data,file)print('Wrote JSON data to{}'.format(file_name))withopen(file_name,'r')asfile:loaded_data=json.load(file)print('Read JSON data from{}:'.format(file_name))print(loaded_data)Standard libraryoriginalimportos# Get the current working directorycwd=os.getcwd()print(f"Current working directory:{cwd}")# List files and directories in the current directoryprint("Files and directories in the current directory:")foriteminos.listdir(cwd):print(item)# Create a new directorynew_dir="example_directory"os.makedirs(new_dir,exist_ok=True)print(f"Created new directory:{new_dir}")# Rename the directorynew_name="renamed_directory"os.rename(new_dir,new_name)print(f"Renamed directory from{new_dir}to{new_name}")# Remove the directoryos.rmdir(new_name)print(f"Removed directory:{new_name}")importshutilsrc_file="source.txt"dst_file="destination.txt"# Copy a fileshutil.copy(src_file,dst_file)print(f"Copied{src_file}to{dst_file}")# Move a filenew_location="moved.txt"shutil.move(dst_file,new_location)print(f"Moved{dst_file}to{new_location}")# Remove a fileos.remove(new_location)print(f"Removed file:{new_location}")importglob# Find all Python files in the current directoryprint("Python files in the current directory:")forpy_fileinglob.glob("*.py"):print(py_file)importtempfile# Create a temporary file and write content to itwithtempfile.NamedTemporaryFile(mode="w+t",delete=False)astemp_file:temp_file.write("Hello, World!")temp_path=temp_file.nameprint(f"Created temporary file:{temp_path}")# Read the content of the temporary filewithopen(temp_path,"r")astemp_file:content=temp_file.read()print(f"Content of the temporary file:{content}")# Remove the temporary fileos.remove(temp_path)print(f"Removed temporary file:{temp_path}")decompiledimportosimportshutilimportglobimporttempfilecwd=os.getcwd()print('Current working directory:{0}'.format(cwd))print('Files and directories in the current directory:')foriteminos.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:')forpy_fileinglob.glob('*.py'):print(py_file)withtempfile.NamedTemporaryFile('w+t',delete=False)astemp_file:temp_file.write('Hello, World!')temp_path=temp_file.nameprint('Created temporary file:{0}'.format(temp_path))withopen(temp_path,'r')astemp_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))DevelopmentSetuppoetryinstall
poetryrunpre-commitinstallSetOPENAI_API_KEYenvironment variable. If you're usingdirenv, you can use.envrc.templateas a template.
Putsrc/pychd/logging.conf. You can copysrc/pychd/logging.conf.templatelike this:cpsrc/pychd/logging.conf.templatesrc/pychd/logging.conf