In Python, "link" refers to several distinct concepts depending on the context: object references, data structures like linked lists, and filesystem links (symbolic and hard links).
Object references
At its most fundamental level, the "link" in Python is the object reference. Every variable is a reference to an object, not a container holding the object itself. When you perform an assignment, you are simply binding a name to an object.
The key concepts
-
Variable assignment: When you write
a = [1, 2], the variableais a reference that "links" to a list object in memory. -
Shared references: If you then write
b = a, a new list object is not created. Instead, the variablebis assigned as a new reference that points to the exact same list object asa. This means that if you modify the list throughb, the change is also visible througha.pythona = [1, 2, 3] b = a b.append(4) print(a) # Output: [1, 2, 3, 4]Use code with caution.
-
Identity vs. equality: Because of this reference model, Python has two ways to check for sameness:
- Equality (
==): Checks if the values of the objects are the same. - Identity (
is): Checks if two variables reference the exact same object in memory.
python
list1 = [1, 2, 3] list2 = [1, 2, 3] list3 = list1 print(list1 == list2) # Output: True (values are the same) print(list1 is list2) # Output: False (different objects in memory) print(list1 is list3) # Output: True (both reference the same object)Use code with caution.
- Equality (
-
Mutation vs. re-assignment: The behavior of a variable depends on whether the object it links to is mutable or immutable.
- Mutable objects (e.g., lists, dictionaries): Can be changed in place, so changes are seen by all references.
- Immutable objects (e.g., numbers, strings, tuples): Cannot be changed. Re-assigning a variable that holds an immutable object simply makes it point to a new object.
Linked list data structure
While not a built-in type, a linked list is a user-defined data structure where each element, called a "node," contains a link or reference to the next node in the sequence. This is a core computer science concept that you can implement in Python.
How it works
- Nodes: A linked list is built from individual node objects. Each node typically holds a piece of data and a reference to the next node.
- Implementation: A Python class can represent a node, with an attribute for its value and another for the link to the next node.
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
Use code with caution.
Advantages and uses
- Efficient insertions/deletions: Adding or removing elements at the beginning of a linked list is very fast, as you only need to re-link a few references.
- Dynamic size: Unlike arrays, linked lists can grow and shrink with the data, without needing to pre-allocate memory.
Filesystem links
Python's os module provides functions for interacting with the operating system, including the creation of filesystem links.
Symbolic links (symlinks)
Also known as "soft links," a symbolic link is a special file that acts as a pointer or shortcut to another file or directory.
-
Creation: Use
os.symlink(src, dst)to create a symbolic link atdstthat points tosrc. -
Cross-filesystem: Symbolic links can point to files on different storage partitions.
-
Example:python
import os os.symlink('/path/to/original_file.txt', '/path/to/link_to_file.txt')Use code with caution.
Hard links
A hard link is another name for an existing file. All hard links to a file share the same inode (the data's address on the disk), and the file's data is only deleted when the last hard link is removed.
-
Creation: Use
os.link(src, dst)to create a hard link nameddstthat points to the same file data assrc. -
Same filesystem: Hard links can only exist on the same filesystem as the original file.
-
Example:python
import os os.link('original.txt', 'hard_link.txt')Use code with caution.
Other "links" in Python
Beyond these core meanings, the term "link" also appears in other specialized contexts:
- Web links (URLs): Libraries like
urllibandrequestsare used to open, parse, and interact with URLs. - Web scraping: Frameworks like Selenium might use selectors like
find_element_by_link_textto locate and click hyperlinks on a web page. - Web frameworks: Libraries like
hyperlinkoffer a more robust and Pythonic way to handle URL objects. - Modules and packages: The
importstatement creates a link to an external module, making its functions and classes available in the current scope. - Software linking: When discussing how Python integrates with C libraries (e.g., via
ctypes), the process of compilation and linking shared objects is a key concept.
Summary table of "link" concepts
| Concept | Explanation | Context |
|---|---|---|
| Object Reference | A variable acting as a named reference or pointer to an object in memory. | Fundamental to the Python language model. |
| Linked List | A user-defined data structure where each node contains a reference (link) to the next node. | Computer science algorithms, dynamic data storage. |
| Symbolic Link | A filesystem object that points to another file or directory (a shortcut). | Operating system, os and pathlib modules. |
| Hard Link | A filesystem entry that points directly to a file's data (same inode). | Operating system, os and pathlib modules. |
| URL (Web Link) | A Uniform Resource Locator, referencing a web resource. | Web development, libraries like urllib and requests. |
| Module Linkage | The process of importing a module, linking its code into the current program. | Python code organization, import statement. |