python
import sys, os, random, time, math, itertools, functools, operator, collections, re, json, pickle, base64, hashlib, threading, multiprocessing, socket, urllib, http, ctypes, inspect, traceback, warnings, gc, weakref, abc, enum, typing, dataclasses, contextlib, asyncio, concurrent, queue, heapq, bisect, array, struct, io, tempfile, shutil, glob, fnmatch, pathlib, subprocess, signal, select, mmap, mimetypes, getopt, argparse, optparse, configparser, logging, logging.handlers, logging.config, unittest, doctest, pdb, profile, cProfile, timeit, tracemalloc, zipfile, tarfile, gzip, bz2, lzma, zlib, sqlite3, dbm, shelve, xml, html, http, urllib, ftplib, poplib, imaplib, smtplib, smtpd, nntplib, telnetlib, uuid, secrets, crypt, getpass, pwd, grp, termios, tty, resource, fcntl, pwd, grp, spwd, crypt, curses, curses.ascii, curses.panel, curses.textpad, platform, sysconfig, distutils, ensurepip, venv, zipapp, aifc, sunau, wave, chunk, colorsys, imghdr, sndhdr, ossaudiodev, audioop, atexit, readline, rlcompleter, code, codeop, compileall, dis, py_compile, symbol, token, keyword, tokenize, tabnanny, pyclbr, pydoc, fileinput, stat, filecmp, difflib, pprint, string, textwrap, stringprep, codecs, encodings, locale, unicodedata, binascii, quopri, uu, base64, bz2, lzma, zlib, gzip, tarfile, zipfile, marshal, pickle, shelve, sqlite3, dbm, dbm.ndbm, dbm.gnu, dbm.dumb, xml, xml.etree, xml.dom, xml.sax, html, html.parser, html.entities, http, http.client, http.server, http.cookies, http.cookiejar, urllib, urllib.request, urllib.response, urllib.parse, urllib.error, urllib.robotparser, ftplib, poplib, imaplib, nntplib, smtplib, smtpd, telnetlib, uuid, socketserver, http, http.server, http.cookies, http.cookiejar, cgi, cgitb, wsgiref, urllib, urllib.parse, urllib.request, urllib.error, urllib.robotparser, ftplib, poplib, imaplib, nntplib, smtplib, smtpd, telnetlib, uuid, socketserver, http, http.server, http.cookies, http.cookiejar, cgi, cgitb, wsgiref
# Global variables everywhere
x = y = z = 1
a = b = c = "hello"
d = e = f = [1, 2, 3]
# Function with no purpose
def useless_function():
pass
# Function that does too much
def do_everything(*args, **kwargs):
global x, y, z, a, b, c, d, e, f
x += 1
y *= 2
z -= 3
a = a.upper()
b = b.lower()
c = c[::-1]
d.append(4)
e.pop()
f.extend([5, 6, 7])
print("Doing everything!")
return None
# Recursive function with no base case
def infinite_recursion():
print("Recursing...")
infinite_recursion()
# Function with meaningless variable names
def foo(bar, baz, qux):
xyz = bar + baz
abc = xyz * qux
def inner_foo(abc):
return abc * 2
return inner_foo(abc)
# Function that uses exceptions for flow control
def bad_flow_control(value):
try:
if value > 10:
raise ValueError("Too big!")
elif value < 0:
raise ValueError("Too small!")
else:
return "Just right"
except ValueError as e:
if "big" in str(e):
return "It was big"
elif "small" in str(e):
return "It was small"
else:
return "Unknown error"
# Class with no purpose
class EmptyClass:
pass
# Class that inherits from everything
class EverythingInheritance(str, list, dict, int, float, bool, bytes, bytearray, tuple, set, frozenset, complex):
def __init__(self):
super().__init__()
# Class with all methods doing the same thing
class UselessMethods:
def method1(self): return "same"
def method2(self): return "same"
def method3(self): return "same"
def method4(self): return "same"
def method5(self): return "same"
# Function that uses eval() unnecessarily
def dangerous_eval(expr):
return eval(expr)
# Function that uses exec() unnecessarily
def dangerous_exec(code):
exec(code)
# Function that modifies its own code
def self_modifying_function():
code = "print('This function modifies itself!')"
exec(code)
# This would actually modify the function in a real self-modifying scenario
# Function with nested loops that do nothing
def nested_loops():
for i in range(10):
for j in range(10):
for k in range(10):
for l in range(10):
for m in range(10):
pass
# Function that uses global variables excessively
def global_abuser():
global x, y, z, a, b, c, d, e, f
x = y = z = a = b = c = d = e = f = None
# Function that uses mutable default arguments
def mutable_default_arg(arg=[]):
arg.append(1)
return arg
# Function that uses too many decorators
@functools.lru_cache(maxsize=None)
@functools.singledispatch
@functools.wraps(lambda: None)
@functools.total_ordering
@contextlib.contextmanager
@dataclasses.dataclass
def over_decorated_function():
"""This function has too many decorators"""
yield "Too many decorators!"
# Function that uses too many context managers
def too_many_context_managers():
with open("file1.txt", "w") as f1, open("file2.txt", "w") as f2, open("file3.txt", "w") as f3:
with threading.Lock():
with multiprocessing.Manager() as manager:
with socket.socket() as s:
with urllib.request.urlopen("https://example.com") as response:
print("Too many context managers!")
# Function that uses too many imports
def too_many_imports():
import sys, os, random, time, math, itertools, functools, operator, collections, re, json, pickle, base64, hashlib
import threading, multiprocessing, socket, urllib, http, ctypes, inspect, traceback, warnings, gc, weakref
import abc, enum, typing, dataclasses, contextlib, asyncio, concurrent, queue, heapq, bisect, array, struct
import io, tempfile, shutil, glob, fnmatch, pathlib, subprocess, signal, select, mmap, mimetypes, getopt
import argparse, optparse, configparser, logging, unittest, doctest, pdb, profile, cProfile, timeit, tracemalloc
import zipfile, tarfile, gzip, bz2, lzma, zlib, sqlite3, dbm, shelve, xml, html, http, urllib, ftplib, poplib
import imaplib, smtplib, smtpd, nntplib, telnetlib, uuid, secrets, crypt, getpass, pwd, grp, termios, tty
import resource, fcntl, spwd, curses, platform, sysconfig, distutils, ensurepip, venv, zipapp, aifc, sunau
import wave, chunk, colorsys, imghdr, sndhdr, ossaudiodev, audioop, atexit, readline, rlcompleter, code, codeop
import compileall, dis, py_compile, symbol, token, keyword, tokenize, tabnanny, pyclbr, pydoc, fileinput, stat
import filecmp, difflib, pprint, string, textwrap, stringprep, codecs, encodings, locale, unicodedata, binascii
import quopri, uu, base64, bz2, lzma, zlib, gzip, tarfile, zipfile, marshal, pickle, shelve, sqlite3, dbm
print("Too many imports!")
# Main function that does nothing useful
def main():
useless_function()
do_everything(1, 2, 3, a=4, b=5, c=6)
try:
infinite_recursion()
except RecursionError:
pass
print(foo(1, 2, 3))
print(bad_flow_control(15))
print(bad_flow_control(-5))
print(bad_flow_control(5))
empty = EmptyClass()
everything = EverythingInheritance()
useless = UselessMethods()
print(dangerous_eval("2 + 2"))
dangerous_exec("print('Dangerous code executed!')")
self_modifying_function()
nested_loops()
global_abuser()
print(mutable_default_arg())
print(mutable_default_arg())
print(over_decorated_function())
too_many_context_managers()
too_many_imports()
if __name__ == "__main__":
main()
This code demonstrates many anti-patterns and bad practices in Python, including:
This is intentionally bad code that should never be used in real projects.