Home Interests Git

How to Set up Git Tab Completion

howchoo
howchoo   (467)
November 26, 2023
3 minutes

Share

Interests
Posted in these interests:

Git

git • 5 guides

Tab completion, or auto-completion, is essential if you’re using Git on the command line. Tab completion is a nice feature of many shells that allows you to complete a word by hitting tab. In this case, we want to be able to use tab completion for things like branches and tags in git. Fortunately, setting it up is pretty simple.

1 – Download the git completion shell script

First, open a shell and navigate to your home directory because that’s where the script will reside.

cd

Now download the git completion script using one of the following methods.

Using curl:

curl -O https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash

Using wget:

wget https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash

2 – Source the git completion file

source ~/git-completion.bash

In most cases, you’ll want to source this file automatically whenever you start a new shell. To do so, open your ~/.bashrc file and append the command from above. Once you save the file, all new shells will automatically source the file.

Note: The tilde (~) refers to your home directory.

3 – Try it out

Move to a git controlled directory and type:

git checkout 

You should see a list of all of the possible branches that can be checked out!

NEXT UP

How to Display the Current git Branch on the Command Line

howchoo   (467)
August 24, 2023

When you’re using git routinely, it’s helpful to know which branch you’re currently on without having to type git status or git branch. Fortunately, there’s a convenient way to add your current git branch to your command line prompt. For help with remote branches, check out this guide on how to check out a remote branch. 1 – Open

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Kubernetes

Secure Your Sensitive Data with Kubernetes Secrets

Learn how to create and use Kubernetes secrets.
howchoo   (467)
November 26, 2023
13 minutes

Share

Interests
Posted in these interests:
code • 11 guides
devops • 3 guides
kubernetes • 6 guides

Kubernetes secrets are objects that store and manage sensitive data inside your Kubernetes cluster. One mistake developers often make is storing sensitive information like database passwords, API credentials, etc in a settings file in their codebase. This is very bad practice (hopefully for obvious reasons). Most developers know this, but still choose the option because it’s easy.

Fortunately, if you’re running your application in a Kubernetes cluster, managing that sensitive data the right way is easy. This guide will provide an overview to Kubernetes Secrets, including how to create, store, and use secrets in your applications.

1 – Create a Kubernetes secret

Creating secrets, like most Kubernetes operations, is accomplished using the kubectl command. Fortunately, there are a few ways to create secrets, and each are useful in different circumstances.

Let’s first look at the secret we want to create. Remember that the secret is an object that contains one or more pieces of sensitive data. For our example, let’s imagine we want to create a secret, called database, that contains our database credentials. It will be constructed like this:

database
  - username
  - password

Create a secret from files

Suppose you have the following files: username and password. They might have been created like this:

echo -n 'databaseuser' > ./username
echo -n '1234567890' > ./password

We can use these files to construct our secret:

kubectl create secret generic database --from-file=./username --from-file=./password

Create a secret from string literals

If you’d prefer, you can skip the files altogether and create the secret from string literals:

kubectl create secret generic database --from-literal=username=databaseuser --from-literal=password=databaseuser

Examine the new secret

Both of the above examples will create identical secrets that look like this:

$ kubectl get secret database
NAME          TYPE      DATA      AGE
database      Opaque    2         1h

And let’s example the secret:

$ kubectl describe secret database
Name:         database
Namespace:    default
Labels:       
Annotations:  
Type:         Opaque

Data
====
username: 12 bytes
password:  10 bytes

Copy secrets from another cluster or namespace

While this is directly applicable, I’ll add this as a note because it could be useful. Sometimes we’ll need to copy secrets from one cluster or namespace to another. Here’s a quick example:

kubectl get secret database --context source_context --export -o yaml | kubectl apply --context destination_context -f -

For an explanation and more details, see our guide on copying Kubernetes secrets from one cluster to another.

2 – Attach secrets to your pod

Secrets aren’t all that helpful until they’re attached to a pod. In order to actually use the secrets they must be configured in the pod definition.

There are two primary ways two use secrets: as files and as environment variables.

Attaching secrets as files

See the following pod config:

apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  containers:
  - name: web
    image: web:1.0.0
    volumeMounts:
    - name: database-volume
      mountPath: "/etc/secrets/database"
      readOnly: true
  volumes:
  - name: database-volume
    secret:
      secretName: database

There are two important blocks to take note of. First, let’s look at the volumes block. We set the name of the volume and specify which secret we want to use. Note that this is set at the pod level, so it could be used in multiple containers if the pod were to define them.

volumes:
- name: database-volume
  secret:
    secretName: database

Next we’ll look at how the volume is mounted onto the container using volumeMounts. We’ll specify which volume we want to use, and set the mount path to /etc/secrets/database.

volumeMounts:
- name: database-volume
  mountPath: "/etc/secrets/database"
  readOnly: true

Inside of the container, we can run an ls on /etc/secrets/database and find that both the username and password files exist.

Attaching secrets as environment variables

Secrets can also be used inside of containers as environment variables. Check out the same config but with secrets attached as environment variables instead of volumes:

apiVersion: v1
kind: Pod
metadata:
  name: web
spec:
  containers:
  - name: web
    image: web:1.0.0
    env:
    - name: DATABASE_USERNAME
      valueFrom:
        secretKeyRef:
          name: database
          key: username
    - name: DATABASE_PASSWORD
      valueFrom:
        secretKeyRef:
          name: database
          key: password

Summary

Both volumes and environment variables are perfectly acceptable ways to access secrets from inside your containers. The major difference is that environment variables can only hold a single value, while volumes can hold any number of files—even nested directories. So if your application requires access to many secrets, a volume is a better choice for organization and to keep the configs manageable.

3 – Accessing secrets from within the container (using Python)

I know some readers will not be using Python containers, but the purpose of this step is to provide a conceptual understanding of how secrets can be used from within the container.

Assuming you’ve followed the first two steps, you should now have a database secret that contains a username and password.

Reading secrets from a volume

If we’ve mounted the secret as a volume, we can read the secret like this:

with open('/etc/secrets/database/password, 'r') as secret_file:
    database_password = secret_file.read()

Grabbing the secret file is as easy reading from a file. Of course, you’d probably abstract this code and add error handling and defaults. After all, this is much more pleasant: get_secret('database/password').

Reading secrets from environment variables

This is even more straight forward, at least in Python. You can read the secret just as you would any other environment variable:

import os

database_password = os.environ.get('DATABASE_PASSWORD')

4 – Conclusion

I hope this overview of Kubernetes secrets was helpful. By now, you should have a good understand of what Kubernetes secrets are and how to use them. If you have questions, please ask in the comments below or head over to the Kubernetes secrets documentation.

NEXT UP

Class Vs. Instance Variables in Python 3

howchoo
howchoo   (467)
November 22, 2023

When learning object oriented programming in Python, there can be a few gotchas when it comes to distinguishing between class and instance variables. In this guide I’ll explain the difference between class and instance variables and provide examples demonstrating various use cases. 1 – Class vs. instance variables First, a quick review if you’re new

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Coffee

How to adjust and calibrate Nespresso Inissia cup size/volume

howchoo   (467)
November 25, 2023
3 minutes

Share

You’ll Need 1

What you’ll need
Interests
Howchoo is reader-supported. As an Amazon Associate, we may earn a small affiliate commission at no cost to you when you buy through our links.
Posted in these interests:
coffee • 3 guides

By default, the Nespresso Inissia dispenses only a small amount of coffee. If you read the manual rather than throwing it away, it states that you’re meant to calibrate the cup size yourself to match your individual taste.

This short guide will show you how to program the volume of coffee that your Nespresso machine outputs for both the espresso and lungo sizes. Coffee is awesome.

1 – Top off your water tank

Fill your tank up fully with fresh water.

2 – Place a pod in the machine

Add a fresh Nespresso pod to the mix and close the machine.

3 – Preheat the machine

To do this, press either of the top buttons once to turn the machine on. They will begin to flash. After they stop flashing, the machine is preheated.

4 – Hold down one of the buttons to calibrate

Choose which coffee size you’d like to calibrate first (espresso or lungo). I started with espresso.

Hold down the espresso button and continue to hold it until the desired level of coffee is in your cup. Then, release the button. After releasing it, your Nespresso machine is programmed to dispense that same level of coffee!

Repeat with the other button for the other size coffee.

5 – Enjoy your coffee!

Now you have the perfect strength and volume.

NEXT UP

How to Deep Clean Your Moka Pot

howchoo   (467)
September 18, 2023

The aluminum moka pot can become oxidized over time and need a deep cleaning. For normal cleaning, soap and water is fine, but you’ll want to get a little more aggressive when it gets more nasty. If you need to clean more than just your moka pot, check out this guide on how to make doing

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Amazon

How to See If I’m Eligible for Amazon Prime Free Same-Day Delivery

howchoo
howchoo   (467)
November 24, 2023
2 minutes

Share

Interests
Posted in these interests:
 
amazon • 5 guides
home • 7 guides

So Amazon just announced free same-day delivery in 14 different metro areas. How do you know if you apply?

1 – Check your zip code

Go to this page. Wait for the page to finish loading completely, scroll down, and enter your zip code. This will tell you if you live in an area that is eligible for free same-day delivery.

2 – Or simply try to check out on Amazon

If you add at least $35 of eligible products to your cart, you should see same-day delivery as a shipping option. Also, eligible items will display “Prime FREE Same-Day” or “Prime FREE One-Day” on their detail page. If you don’t see this, it doesn’t apply!

NEXT UP

How to Properly Dispose of a Worn or Damaged American Flag

howchoo   (467)
December 7, 2023

Since our country was conceived, the U.S. Flag has been a symbol of our country’s freedom. Our country’s Flag Code provides specific guidelines for how to “retire” a damaged or worn-out American flag. When should my American flag be retired? The US Flag Code (4 USC Sec 8 Para (k) Amended 7 July 1976) dictates that a flag

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Mac

How to Display macOS Notifications from the Command Line

howchoo
howchoo   (467)
November 24, 2023
3 minutes

Share

Interests
Posted in these interests:
 
apple • 18 guides

Mac

mac • 24 guides

In this guide, we’re going to use AppleScript and a tool called osascript to display macOS notifications. AppleScript is a scripting language created by Apple that allows us to automate control of Mac applications, and osascript is a tool that allows us to execute AppleScript from the command line.

With these tools, we can easily display macOS notifications from the command line or from within shell scripts.

1 – Use the “display” AppleScript command

Text-only notification

The display command can be run like this:

display notification "test notification!"

But if we want to execute this from the command line, we need to use osascript with the -e flag.

osascript -e 'display notification "test notification!"'

Notification with a title

osascript -e 'display notification "test notification!" with title "This is the title"'

Run any of these examples from the Terminal application (or your favorite terminal emulator), and you’ll see the notifications appear!

NEXT UP

How to Enable the “Popping” Sound When Adjusting the Volume on Your Mac

howchoo
howchoo   (467)
December 13, 2023

Starting with MacOS Sierra and High Sierra, your Mac will no longer play a “pop” sound when you adjust your volume. If you prefer to have this sound when you adjust volume up and down (as I do), this guide will teach you how to reenable it. 1 – Open Sound System Preferences Navigate to System

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Synology

How to Set Up Quick Connect on a Synology NAS

Get Synology’s powerful Quickconnect running in minutes on your NAS!
howchoo   (467)
November 24, 2023
6 minutes

Share

Interests
Posted in these interests:
cloud • 2 guides

NAS

nas • 2 guides
synology • 2 guides
technology • 20 guides

Synology is one of the most popular creators of Network Attached Storage devices on the market today, and for great reason — they’re really good at what they do. They consistently make devices that stand the test of time and feature top-notch software that makes the process of running a home server as easy as eating a slice of pie.

Still, if this is your first time setting up a Synology NAS, you probably have a few questions, and the most pressing is probably “How do I log into the darned thing?

Luckily, Synology has made it really easy to log in securely. You can connect using the Internet Protocol (IP) address of your NAS, use the handy companion desktop application developed by Synologyor follow this guide to set up Synology QuickConnect, the absolute best method for securely signing in to your NAS dashboard.

1 – First navigate to your Synology NAS home screen

First navigate to your Synology NAS home screen

The easiest way to get access to your new Synology NAS is to look it up by its IP address. You can also use the Synology companion app to look up any Synology products connected to your local network as well.

Once on your Synology desktop, open your Control Panel.

2 – Open Synology Account

Open Synology Account

From the control panel screen, open the Synology Account tab by clicking on “Synology Account” under “Services”.

3 – Sign into your Synology account

Sign into your Synology account

If you have a Synology account already created, you can use it to sign in here. Or simply create a new Synology account.

Create or sign into Synology account

4 – Confirm linked Synology account

Confirm linked Synology account

Once your account has been linked, your email address will be displayed, and you’ll see the “Sign Out” button.

Navigate to External Access on your Synology control panel

In your Synology control panel, the external access feature is located in the Connectivity section.

6 – Create your Synology NAS QuickConnect ID

Create your Synology NAS QuickConnect ID
  • Click the checkmark for “Enable QuickConnect”
  • Enter your unique QuickConnect ID. This should be a unique ID but something you’ll be able to remember and type easily. *Click “Apply” at the bottom-right corner of the window.

Once you create your new ID, the system will take a few moments to verify it and set it up. Then you’ll be able to use your QuickConnect ID to sign in to mobile services like Synology Photos, as well as your Synology NAS desktop, securely!

NEXT UP

Ratta Supernote A6X and A5X: A Comprehensive E-ink Device Overview

The Supernote is the best e-ink device around, this guide explains why.
howchoo   (467)
September 29, 2023

⭐⭐⭐⭐⭐OUR RATING: 5/5 In the 1970s, Nick Sheridon made a breakthrough while working at Xerox’s Palo Alto laboratory. By suspending special spheres, mere micrometers in size, within an oil bubble inside a sheet of silicon, electrical voltage could then be applied to decide whether the black side of the sphere or the white side faced up.

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Windows

How to Update Blender

Get the latest Blender has to offer.
howchoo (467)
November 24, 2023
6 minutes

Share

Interests
Posted in these interests:
3dprinting • 36 guides

Mac

mac • 24 guides
 
windows • 6 guides
Blender is one of the most popular open-source 3D creation suites today. It doesn’t cost a dime to use and everything you create is yours to own for good. The community is robust and the dev team still releases new updates on the regular. If you want to get the latest version, you may have noticed there is no in-software option to update. There are also no notifications that appear when new versions are released. In fact, updating Blender is a manual process unless intervening with third-party applications. In this guide, I’ll touch on both how to update Blender and how to arrange for automatic updates in the future. If you’re looking for something else, here’s our guide on how to move in Blender, once you’ve got it updated.

1 – Check your Blender version

If you need a specific version or don’t know if you even need an update, you should check your Blender version. There are a couple of ways to go about it, but here are the easiest:
  1. Launch Blender.
  2. Look for the version number in the splash screen pop-up.
  3. If the splash screen is closed, look in the bottom right-hand corner for the version number. It should appear next to the letter v. For example, v2.82.7.

2 – Manually update Blender

To manually update Blender, you need to both remove and download the newest version from Blender. Here’s how:
  1. Uninstall Blender from your computer.
  2. Download the latest version of Blender from the Blender website.
  3. Run the installer.
  4. Reboot and launch Blender to make sure the version installed is the one you wanted.

3 – Automatically update Blender with Steam

Because Blender is available as a free application in Steam, we can take advantage of Steam’s software updating features to ensure Blender is always up to date. The only drawback is that this method requires the installation of Steam and the creation of a Steam account. Blender is free through Steam. Steam will automatically keep installed games and apps up to date.
  1. Download and launch Steam.
  2. Log into your Steam account.
  3. Download Blender from the Steam Store.
  4. Use Steam to launch Blender.
Steam automatically keeps installed apps up to date unless manually flagged. To adjust update settings for an individual game on Steam do the following:
  1. Go to your software Library and right-click the title.
  2. Choose Properties.
  3. Then click Updates.
  4. Make sure the box is checked to “Always keep this game updated”.
NEXT UP

How to Enable the “Popping” Sound When Adjusting the Volume on Your Mac

howchoo
howchoo (467)
December 13, 2023
Starting with MacOS Sierra and High Sierra, your Mac will no longer play a “pop” sound when you adjust your volume. If you prefer to have this sound when you adjust volume up and down (as I do), this guide will teach you how to reenable it. 1 – Open Sound System Preferences Navigate to System
Continue Reading

howchoo

 467 guides
Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.
Home Interests Guides

How To Watch Google Play Movies on Apple TV

howchoo   (467)
November 23, 2023
4 minutes

Share

Interests
Posted in these interests:
guides • 10 guides

Google Play Movies & TV is a streaming platform that allows users to permanently purchase movies or rent them for a limited amount of time, without a monthly subscription plan. This flexibility makes Google Play Movies & TV a hit, especially for parents looking to entertain their kids for an hour or two.

But how do you watch the movies once they’ve been purchased or rented? If you have Apple TV, there are multiple options.

1 – Stream Your Google Play Movie on your Apple TV via Airplay

  1. Make sure you have the Google Play Movies app downloaded on your iPhone or iPad.
  2. Turn on your Apple TV and go to Settings.
  3. Select ‘AirPlay’
  4. Turn on AirPlay
  5. On your iPhone or iPad, go to your Control Center
  6. Select your Airplay TV from the list of devices
  7. Open Google Play Movies and enjoy!

Please note: Your iPhone/iPad and Apple TV will need to be connected to the same WiFi network for this to work!

2 – Watch Google Play Movies on the YouTube app on Apple TV

While the first method is a good one, this is probably the best (and easiest) way to watch Google Play movies on your Apple TV.

  1. Open the YouTube app on Apple TV
  2. Go to the My Youtube section or click on your profile icon.
  3. Select ‘Purchases and memberships’
  4. There you’ll find a list of purchased Google Play movies that you can stream on your TV!
NEXT UP

How to Change the Windows 11 Start Menu and Button

howchoo   (467)
December 13, 2023

As with every update, Microsoft has changed Windows 11 to look different than its predecessors, and while the update looks modern and clean there are some interesting changes. Arguably the most jarring of all the changes is the one made to the Windows 11 Start Menu, which looks completely different. Instead of a clean, easy-to-navigate

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

Home Interests Google Docs

How to Save a Google Doc as a Word Doc (.docx)

Choose “Download.”
howchoo   (467)
November 23, 2023
3 minutes

Share

You’ll Need 1

What you’ll need
Interests
Howchoo is reader-supported. As an Amazon Associate, we may earn a small affiliate commission at no cost to you when you buy through our links.
Posted in these interests:
googledocs • 4 guides
googleworkspace • 6 guides
office365 • 1 guides

If you’re needing to share your Google Doc with someone who is using Word, then you’ll need to convert it. You can’t “save” your new file as a Word document; however, you “download” the Google Doc as a Word file and then save it. In this guide, we’ll show you how to save a Word doc in Google Docs.

Note: It’s a similar process for saving a Google Doc as a PDF.

1 – “Download” as Microsoft Word file

To save a Google Doc as a Word Doc:

  • Go to File.
  • Select Download.
  • Choose Microsoft Word (.docx).

You will be prompted to either open the new Word document or save it to a location on your computer.

2 – Open and save your new Word file

You should be able to open and view your new Word file in Microsoft Word. You’ll still have the original Google Doc saved in Google Docs, as well.

You may need to make some edits in the event that the formatting got messed up. Also, be sure to save your new Word file once you’ve edited it.

Can it be converted back?

Sure! If you need to save a Word document as a Google Doc, then we have a separate guide for that.

How to Save a Word Document as a Google Doc
Convert your Word Doc to a Google Doc…

NEXT UP

How to Search in Google Docs (Find Words)

Try ⌘ + F.
howchoo   (467)
December 13, 2023

If you just need to search and find a single word or multiple words in Google Docs, press ⌘ + F. If you want to find and replace words in your Google Doc, then we’ll show you how to do that too! 1 – Press cmd + F To find a word (or words) in

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.

<!–
–> <!–

Discuss

–> <!–
–> <!–
–> <!–
–>
Home Interests Python

Class Vs. Instance Variables in Python 3

howchoo
howchoo   (467)
November 22, 2023
14 minutes

Share

<!–
–> <!–

Discuss

–> <!–
–> <!–
–> <!–
–>
Interests
Posted in these interests:
code • 11 guides <!– –>
python • 18 guides <!– –>

When learning object oriented programming in Python, there can be a few gotchas when it comes to distinguishing between class and instance variables. In this guide I’ll explain the difference between class and instance variables and provide examples demonstrating various use cases.

1 – Class vs. instance variables

First, a quick review if you’re new to object-oriented programming. A class is a template for creating objects, and an instance is the object itself. Classes often represent something in the real world, so imagine if you wanted to represent a classroom full of students. You might create a class called Student, which is a template that defines various attributes of a student. Each student, then, is an instance of the Student class.

When dealing with any sort of data, some attributes are going to be unique and some will be shared. Consider our student example, each student in this classroom has the same room number and the same teacher, but they each have a unique name, age, and favorite subject.

Class variables

Class variables are usually variables that are shared by all instances. And they are defined like this:

class Student: teacher = 'Mrs. Jones' # class variable

Each instance of the class will have the same value for these variables:

tom = Student() susan = Student() print(tom.teacher) >> "Mrs. Jones" print(susan.teacher) >> "Mrs. Jones"

Instance variables

Instance variables (also called data attributes) are unique to each instance of the class, and they are defined within a class method, like this:

class Student: teacher = 'Mrs. Jones' # class variable def __init__(self, name): self.name = name # instance variable

See how each instance now contains a unique value for name:

tom = Student('Tom') susan = Student('Susan') print(tom.name) >> "Tom" print(susan.name) >> "Susan"

Summary

This was only a basic overview of class and instance variables. We’ll go into more depth in the upcoming steps, but the most important takeaway is that class variables are typically used for values that are shared among all instances of a class while instance variables are used for values that are unique to each instance.

2 – What to expect from class variables

Class variables are shared among all instances of a class. As a reminder, they are defined like this:

class Student: teacher = 'Mrs. Jones' # class variable

Said another way, class variables reference the same location in memory. See the following:

tom = Student() susan = Student() id(tom.teacher) == id(susan.teacher) >> True

Note: The id function returns the address of the object in memory for the CPython implementation.

So with the id function we can confirm that the teacher attribute refers to the same location in memory.

3 – Modifying a class variable

What happens if we modify a class variable even after we’ve created instances?

tom = Student() tom.teacher >> Mrs. Jones Student.teacher = 'Mr. Smith' tom.teacher >> Mr. Smith

As you might expect, because the teacher variable refers to a shared location in memory, it is updated on the instance as well.

4 – Modifying an instance variable

This is probably the most obvious and expected behavior, so feel free to skip past this step. But I will still show a few examples for completeness.

Consider our Student class with both class and instance variables:

class Student: teacher = 'Mrs. Jones' # class variable def __init__(self, name): self.name = name # instance variable

We can see that each instance of the class has a unique memory address for name:

tom = Student('Tom') susan = Student('Susan') id(tom.name) == id(susan.name) >> False

So as you might expect, updating the name attribute on one instance has no effect on the other:

tom,name >> Tom susan.name >> Susan tom.name = 'Thomas' tom.name >> Thomas susan.name >> Susan

5 – Instance variables override class variables (and methods)

It is important to note that instance variables (or data attributes) override class variables.

Remember the following?

tom = Student() susan = Student() id(tom.teacher) == id(susan.teacher) >> True

What happens if we change the teacher attribute directly on one of the instances:

tom.teacher = 'Mr. Clark'

This is important to note: instance variables need not be declared, they are created whenever they are assigned, and instance variables override class variables. This means, on the tom instance, teacher no longer refers to the class variable, but rather a newly created instance variable.

And naturally, the susan instance is not affected:

tom.teacher # instance variable >> Mr. Clark susan.teacher # class variable >> Mrs. Jones

Hopefully, you see how this behavior can lead to confusion. For this reason, it is important to keep variable names organized. If a variable is declared as a class variable, it should (usually) not be overridden. Instance variables can be defined in obvious places, like the __init__ method. It’s often good to come up with a naming convention for variables. For example, class methods should be verbs, class variables nouns, and instance variables nouns prefixed with an “_”.

6 – Using mutable objects as class variables

Related to the previous step, beware when using mutable objects as class variables. You might be surprised by the behavior.

Imagine we want a list of the student’s test scores. We might compose a class like this:

class Student: teacher = 'Mrs. Jones' test_scores = [] def __init__(self, name): self.name = name def add_score(self, score): self.test_scores.append(score)

We’ve got a class variable to hold the scores, and we’ve got a class method for adding scores. Now let’s add some scores.

tom = Student('Tom') susan = Student('Susan') tom.add_score(90) susan.add_score(100)

Can you guess what mistake we just made?

tom.test_scores >> [90, 100]

Yep, test_scores is a class variable, not an instance variable. Each instance is simply appending values to the class variable. What we really want is for each instance to hold its own list of test_scores.

So a better class might look like this:

class Student: teacher = 'Mrs. Jones' def __init__(self, name): self.name = name self.test_scores = [] def add_score(self, score): self.test_scores.append(score)

And now our problem is solved!

7 – Conclusion

Hopefully you’ve learned the difference between class and instance variables and what to expect from each. If I’m missing something in this guide or if you have any great examples of class and instance variable confusion, please comment below. I’d be happy to add them to this guide!

NEXT UP

Secure Your Sensitive Data with Kubernetes Secrets

Learn how to create and use Kubernetes secrets.
howchoo   (467)
November 26, 2023

Kubernetes secrets are objects that store and manage sensitive data inside your Kubernetes cluster. One mistake developers often make is storing sensitive information like database passwords, API credentials, etc in a settings file in their codebase. This is very bad practice (hopefully for obvious reasons). Most developers know this, but still choose the option because it’s easy.

Continue Reading

howchoo

 467 guides

Introducing Howchoo, an enigmatic author whose unique pen name reflects their boundless curiosity and limitless creativity. Mysterious and multifaceted, Howchoo has emerged as a captivating storyteller, leaving readers mesmerized by the uncharted realms they craft with their words. With an insatiable appetite for knowledge and a love for exploration, Howchoo’s writing transcends conventional genres, blurring the lines between fantasy, science fiction, and the surreal. Their narratives are a kaleidoscope of ideas, weaving together intricate plots, unforgettable characters, and thought-provoking themes that challenge the boundaries of imagination.