PythonQuickies: Difference between revisions

From Traxel Wiki
Jump to navigation Jump to search
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
[[Category:Python]]
[[Category:Python]]
= Abstract Base Class =
<syntaxhighlight lang="python" line>
from abc import ABC, abstractmethod
from .event import Event
class ThreadEvent(ABC, Event):
    """
    A class used to represent a post, comment, or reply in a community.
    """
   
    @abstractmethod
    def to_tag(self):
        """
        Returns
        -------
        list
            contains one element which is this event's own tag
        """
        pass
</syntaxhighlight>
= buffering =
= buffering =
Fix CLI buffering in Python with:
Fix CLI buffering in Python with:
Line 7: Line 30:


"-u" means unbuffered, or something
"-u" means unbuffered, or something
= Caching =
= Caching =
== Disable __pycache__ Caching ==
== Disable __pycache__ Caching ==
Line 17: Line 41:
python script.py
python script.py
</pre>
</pre>
= Datetime and Timestamp =
<syntaxhighlight lang="python" line>
from datetime import datetime, timezone
import pytz
print("When including time, use one of the following:")
ts = 0
good_dt = pytz.utc.localize(datetime.utcfromtimestamp(ts))
print(f'pytz.utc.localize(datetime.utcfromtimestamp(ts)) = {good_dt}')
ts = 0
good_dt = datetime.fromtimestamp(ts, timezone.utc)
print(f'datetime.fromtimestamp(ts, timezone.utc) = {good_dt}')
dt_with_tz = good_dt
good_ts = int(dt_with_tz.timestamp())
print(f'int(dt_with_tz.timestamp()) = {good_ts}')
now_dt = pytz.utc.localize(datetime.utcnow())
now_ts = int(now_dt.timestamp())
renow_dt = datetime.fromtimestamp(now_ts, timezone.utc)
print()
print(f'now_dt = pytz.utc.localize(datetime.utcnow()) = {now_dt}')
print(f'now_ts = int(now_dt.timestamp()) = {now_ts}')
print(f'now_dt = datetime.fromtimestamp(now_ts, timezone.utc) = {renow_dt}')
now_ts = int(pytz.utc.localize(datetime.utcnow()).timestamp())
print(f'now_ts = int(pytz.utc.localize(datetime.utcnow()).timestamp()) = {now_ts}')
import time
print(f'now_ts = int(time.time()) = {int(time.time())}')
</syntaxhighlight>
= Decorators =
<syntaxhighlight lang="python" line>
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        func(*args, **kwargs)
        print("Something is happening after the function is called.")
    return wrapper
@my_decorator
def say_hello():
    print("Hello!")
say_hello()
</syntaxhighlight>


= Delayed Type Definitions =
= Delayed Type Definitions =
Line 44: Line 120:
  2054  deactivate
  2054  deactivate
</pre>
</pre>
= Package Info =
* https://pypi.org/project/package-name/
** eg: https://pypi.org/project/itsdangerous/


= Random =
= Random =
Line 53: Line 132:
sorted_stories = sorted(stories, key=lambda x: x['job']['ups'], reverse=True)
sorted_stories = sorted(stories, key=lambda x: x['job']['ups'], reverse=True)
</pre>
</pre>
= Decorators =
= Subclass =
<syntaxhighlight lang="python" line>
<syntaxhighlight lang="python" line>
def my_decorator(func):
# Parent class
     def wrapper(*args, **kwargs):
class Vehicle:
         print("Something is happening before the function is called.")
    def __init__(self, brand, model):
         func(*args, **kwargs)
        self.brand = brand
         print("Something is happening after the function is called.")
        self.model = model
    return wrapper
 
     def display(self):
         print(f"This is a {self.brand} {self.model}.")
 
# Child class
class Car(Vehicle):
    def __init__(self, brand, model, doors):
         super().__init__(brand, model) # Call the __init__ of the parent class
        self.doors = doors
 
    # Overriding the display method of the parent class
    def display(self):
        super().display()  # Call the display method of the parent class
         print(f"It has {self.doors} doors.")


@my_decorator
# Testing the classes
def say_hello():
vehicle = Vehicle("Toyota", "Camry")
    print("Hello!")
vehicle.display()


say_hello()
car = Car("Honda", "Civic", 4)
car.display()
</syntaxhighlight>
</syntaxhighlight>
= Type Safety =
== ==
<pre>
class Car:
    def __init__(self, make: str, year: int) -> None:
        self.make = make
        self.year = year
    def drive(self, speed: float) -> None:
        print(f"Driving at {speed} km/h")
    def new_model(self, year: int) -> Car:
        return Car(self.make, self.year + 1)
# Example usage
car = Car("Toyota", 2022)
car.drive(100.0)  # Valid
car.drive("fast")  # Invalid, but no runtime error (type checker will warn)
</pre>


= Virtual Environments =
= Virtual Environments =
Line 114: Line 228:
zipp==3.16.2
zipp==3.16.2
</pre>
</pre>
= Package Info =
* https://pypi.org/project/package-name/
** eg: https://pypi.org/project/itsdangerous/
= Datetime and Timestamp =
<syntaxhighlight lang="python" line>
from datetime import datetime, timezone
import pytz
print("When including time, use one of the following:")
ts = 0
good_dt = pytz.utc.localize(datetime.utcfromtimestamp(ts))
print(f'pytz.utc.localize(datetime.utcfromtimestamp(ts)) = {good_dt}')
ts = 0
good_dt = datetime.fromtimestamp(ts, timezone.utc)
print(f'datetime.fromtimestamp(ts, timezone.utc) = {good_dt}')
dt_with_tz = good_dt
good_ts = int(dt_with_tz.timestamp())
print(f'int(dt_with_tz.timestamp()) = {good_ts}')
now_dt = pytz.utc.localize(datetime.utcnow())
now_ts = int(now_dt.timestamp())
renow_dt = datetime.fromtimestamp(now_ts, timezone.utc)
print()
print(f'now_dt = pytz.utc.localize(datetime.utcnow()) = {now_dt}')
print(f'now_ts = int(now_dt.timestamp()) = {now_ts}')
print(f'now_dt = datetime.fromtimestamp(now_ts, timezone.utc) = {renow_dt}')
now_ts = int(pytz.utc.localize(datetime.utcnow()).timestamp())
print(f'now_ts = int(pytz.utc.localize(datetime.utcnow()).timestamp()) = {now_ts}')
import time
print(f'now_ts = int(time.time()) = {int(time.time())}')
</syntaxhighlight>
= Subclass =
<syntaxhighlight lang="python" line>
# Parent class
class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
    def display(self):
        print(f"This is a {self.brand} {self.model}.")
# Child class
class Car(Vehicle):
    def __init__(self, brand, model, doors):
        super().__init__(brand, model)  # Call the __init__ of the parent class
        self.doors = doors
    # Overriding the display method of the parent class
    def display(self):
        super().display()  # Call the display method of the parent class
        print(f"It has {self.doors} doors.")
# Testing the classes
vehicle = Vehicle("Toyota", "Camry")
vehicle.display()
car = Car("Honda", "Civic", 4)
car.display()
</syntaxhighlight>
= Abstract Base Class =
<syntaxhighlight lang="python" line>
from abc import ABC, abstractmethod
from .event import Event
class ThreadEvent(ABC, Event):
    """
    A class used to represent a post, comment, or reply in a community.
    """
   
    @abstractmethod
    def to_tag(self):
        """
        Returns
        -------
        list
            contains one element which is this event's own tag
        """
        pass
</syntaxhighlight>

Latest revision as of 17:28, 8 September 2024

Abstract Base Class

from abc import ABC, abstractmethod

from .event import Event

class ThreadEvent(ABC, Event):
    """
    A class used to represent a post, comment, or reply in a community.
    """
    
    @abstractmethod
    def to_tag(self):
        """
        Returns
        -------
        list
            contains one element which is this event's own tag
        """
        pass

buffering

Fix CLI buffering in Python with:

$ python -u foo.py | tee mylog.log

"-u" means unbuffered, or something

Caching

Disable __pycache__ Caching

$ python -B foo.py
export PYTHONDONTWRITEBYTECODE=1
python script.py

Datetime and Timestamp

from datetime import datetime, timezone
import pytz

print("When including time, use one of the following:")

ts = 0
good_dt = pytz.utc.localize(datetime.utcfromtimestamp(ts))
print(f'pytz.utc.localize(datetime.utcfromtimestamp(ts)) = {good_dt}')

ts = 0
good_dt = datetime.fromtimestamp(ts, timezone.utc)
print(f'datetime.fromtimestamp(ts, timezone.utc) = {good_dt}')

dt_with_tz = good_dt
good_ts = int(dt_with_tz.timestamp())
print(f'int(dt_with_tz.timestamp()) = {good_ts}')

now_dt = pytz.utc.localize(datetime.utcnow())
now_ts = int(now_dt.timestamp())
renow_dt = datetime.fromtimestamp(now_ts, timezone.utc)

print()
print(f'now_dt = pytz.utc.localize(datetime.utcnow()) = {now_dt}')
print(f'now_ts = int(now_dt.timestamp()) = {now_ts}')
print(f'now_dt = datetime.fromtimestamp(now_ts, timezone.utc) = {renow_dt}')

now_ts = int(pytz.utc.localize(datetime.utcnow()).timestamp())
print(f'now_ts = int(pytz.utc.localize(datetime.utcnow()).timestamp()) = {now_ts}')

import time
print(f'now_ts = int(time.time()) = {int(time.time())}')

Decorators

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        func(*args, **kwargs)
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()


Delayed Type Definitions

from __future__ import annotations # allows types to be used before definition

class Foo:
  def add_child(self, a_foo: Foo)
    self.children.append(a_foo)

GUI

Tkinter

Jupyter

 2048  mkdir kiln-jupyter
 2049  cd kiln-jupyter/
 2050  python -m venv venv
 2051  source venv/bin/activate
 2052  pip install jupyter
 2053  jupyter-lab
 2054  deactivate

Package Info

Random

base64.b32encode(os.urandom(64)).decode('utf-8')

Sorting

sorted_stories = sorted(stories, key=lambda x: x['job']['ups'], reverse=True)

Subclass

# Parent class
class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display(self):
        print(f"This is a {self.brand} {self.model}.")

# Child class
class Car(Vehicle):
    def __init__(self, brand, model, doors):
        super().__init__(brand, model)  # Call the __init__ of the parent class
        self.doors = doors

    # Overriding the display method of the parent class
    def display(self):
        super().display()  # Call the display method of the parent class
        print(f"It has {self.doors} doors.")

# Testing the classes
vehicle = Vehicle("Toyota", "Camry")
vehicle.display()

car = Car("Honda", "Civic", 4)
car.display()

Type Safety

class Car:
    def __init__(self, make: str, year: int) -> None:
        self.make = make
        self.year = year

    def drive(self, speed: float) -> None:
        print(f"Driving at {speed} km/h")

    def new_model(self, year: int) -> Car:
        return Car(self.make, self.year + 1)

# Example usage
car = Car("Toyota", 2022)
car.drive(100.0)  # Valid

car.drive("fast")  # Invalid, but no runtime error (type checker will warn)

Virtual Environments

# Check Python version
python3 --version

# Check pip version
pip3 --version

# Install virtualenv
pip3 install virtualenv

# Install venv
sudo apt install python3-venv

# Navigate to your project directory
cd ~/my_project/

# Create virtual environment
python3 -m venv myenv

# Activate virtual environment
source myenv/bin/activate

# Now you can install packages
pip install <your-package>

# Deactivate when you're done
deactivate

What Libs Have I?

$ pip freeze --local
blinker==1.6.2
click==8.1.7
flask==2.3.3
importlib-metadata==6.8.0
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.3
werkzeug==2.3.7
zipp==3.16.2