In Python, there are 2 ways to retrieve a module's path.
Using __file__ Attribute
You can retrieve a module's path using the __file__ attribute. For example,
#!/usr/bin/python3
# Import module
import os
print(os.__file__)
/usr/local/lib/python3.10/os.py
However, there is an important caveat, which is that __file__ does NOT exist if you are running the module on its own.
Using inspect Module
The Path.resolve() method returns the name of the (text or binary) file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.
#!/usr/bin/python3
# Import module
import os
import inspect
print(inspect.getfile(os))
/usr/local/lib/python3.10/os.py
In Python, there are 2 ways to get an absolute file path.
Using abspath Function
The os.path.abspath() method returns a normalized absolutized version of the pathname path. For example,
#!/usr/bin/python3
# Import module
import os
abs = os.path.abspath("file.txt")
print(abs)
/home/python/code/file.txt
On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).
Using pathlib Module
The Path.resolve() method makes the path absolute, resolving any symlinks. A new path object is returned:
#!/usr/bin/python3
# Import module
import pathlib
abs = pathlib.Path("file.txt").resolve()
print(abs)
/home/python/code/file.txt
In Python, using the str.join function is the easiest way to concatenate a list of strings into a single string
Using str.join Function
The str.join() method returns a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method. For example,
#!/usr/bin/python3
s = '-'.join(["a", "c", "b"])
print(s)
a-c-b
.join is faster because it allocates memory only once. Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.
See the following example:
#!/usr/bin/python3
a = "123456"
s = ','.join(a).join(("(",")"))
print(s)
(1,2,3,4,5,6)
In Python, there are 2 ways to get a function name as a string.
Using __name__ Attribute
Using __qualname__ is the preferred method as it applies uniformly. It works on built-in functions as well:
#!/usr/bin/python3
def my_func():
pass
class A():
def getName():
pass
print(my_func.__name__)
print(A.getName.__name__)
# Python 3.3+
print(A.getName.__qualname__)
my_func
getName
A.getName
If you're interested in class methods too, Python 3.3+ has __qualname__ in addition to __name__.
Using inspect Module
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.
See the following example:
#!/usr/bin/python3
# Import module
import inspect
def my_func():
func_name = inspect.currentframe().f_code.co_name
print(func_name)
pass
class A():
def getName():
func_name = inspect.currentframe().f_code.co_name
print(func_name)
pass
my_func()
A.getName()
my_func
getName
sys._getframe also works instead of inspect.currentframe although the latter avoids accessing a private function.
In Python, there are 3 ways to get the size of a file.
Using os.path.getsize Method
The os.path.getsize() method returns the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible. For example,
#!/usr/bin/python3
# Import module
import os
size = os.path.getsize("file.txt")
print(size)
10259
Note: the implementation of os.path.getsize is simply return os.stat(filename).st_size.
Using pathlib Module
You can use pathlib.Path().stat() function, it really simple. For example,
#!/usr/bin/python3
# Python 3.4+
# Import module
import pathlib
stat = pathlib.Path("file.txt").stat()
print(stat.st_size)
10259
Using os.stat Method
The os.stat() method gets the status of a file or a file descriptor.
For example,
#!/usr/bin/python3
# Import module
import os
stat = os.stat("file.txt")
print(stat.st_size)
10259
In Rust, there are 2 ways to reverse a string.
Using rev Function
The str::rev() function reverses an iterator’s direction.
See the following example:
fn main() {
let mut s = "Hello";
println!("{}", s.chars().rev().collect::<String>());
s = "a̐éö";
println!("{}", s.chars().rev().collect::<String>());
}
olleH
̈óe̐a
Using unicode-segmentation Crate
Installation
This crate is fully compatible with Cargo. Just add it to your Cargo.toml:
[dependencies]
unicode-segmentation = "1"
unicode-segmentation Usage
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let mut s = "Hello";
println!("{}", s.graphemes(true).rev().collect::<String>());
s = "a̐éö";
println!("{}", s.graphemes(true).rev().collect::<String>());
}
olleH
öéa̐
In Rust, there are 2 ways to convert float to integer.
Using as Keyword
Executing an as expression casts the value on the left-hand side to the type on the right-hand side.
An example of an as expression:
fn main() {
let a = 3.6415_f64;
let b = a as i64;
println!("{}", b);
}
3
Using round Function
The round() function returns the nearest integer to a number. Round half-way cases away from 0.0.
See the following example:
fn main() {
let a = 3.6415_f64;
let mut b = a.round() as i64;
println!("round: {}", b);
b = a.trunc() as i64;
println!("trunc: {}", b);
b = a.ceil() as i64;
println!("ceil: {}", b);
b = a.floor() as i64;
println!("floor: {}", b);
}
round: 4
trunc: 3
ceil: 4
floor: 3
In Rust, there are 2 ways to remove an element from a vector.
Using retain Function
The vec::retain() function retains only the elements specified by the predicate.
For example,
fn main() {
let mut v = vec![1, 3, 2, 3, 4];
v.retain(|&x| x != 3);
println!("{:?}", v);
}
[1, 2, 4]
Using remove Function
The vec::remove() function removes and returns the element at position index within the vector, shifting all elements after it to the left.
See the following example:
fn main() {
let mut v = vec![1, 3, 2, 3, 4];
// Remove first element
if let Some(pos) = v.iter().position(|x| *x == 3) {
v.remove(pos);
}
println!("{:?}", v);
// Remove last element
v = vec![1, 3, 2, 3, 4];
if let Some(pos) = v.iter().rposition(|x| *x == 3) {
v.remove(pos);
}
println!("{:?}", v);
}
[1, 2, 3, 4]
[1, 3, 2, 4]
Rust Errors
None:
let i = v.iter().position(|x| *x == 5).unwrap();
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:3:42
cannot borrow as mutable:
let v = vec![1, 3, 2, 3, 4];
--> src/main.rs:4:3
|
2 | let v = vec![1, 3, 2, 3, 4];
| - help: consider changing this to be mutable: `mut v`
3 | let i = v.iter().position(|x| *x == 5).unwrap();
4 | v.remove(i);
| ^^^^^^^^^^^ cannot borrow as mutable
In Rust, there are 2 ways to get the string length in characters.
Using chars Function
The str::chars() function returns an iterator over the chars of a string slice.
See the following example:
fn main() {
let mut s = "Hello";
println!("{}", s.chars().count());
s = "a̐";
println!("{}", s.chars().count());
}
5
2
Using unicode-segmentation Crate
Installation
This crate is fully compatible with Cargo. Just add it to your Cargo.toml:
[dependencies]
unicode-segmentation = "1"
unicode-segmentation Usage
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let mut s = "Hello";
println!("{}", s.graphemes(true).count());
s = "a̐";
println!("{}", s.graphemes(true).count());
}
5
1
In Rust, using the read_dir function is the easiest way to list files of a directory.
Using read_dir Function
The fs::read_dir() function returns an iterator over the entries within a directory.
See the following example:
use std::fs;
fn main() {
let paths = fs::read_dir("./").unwrap();
for path in paths {
println!("{}", path.unwrap().path().display())
}
}
./.gitignore
./Cargo.toml
./src
./file.txt
Rust Errors
This function will return an error in the following situations, but is not limited to just these cases:
The provided path doesn’t exist.
The process lacks permissions to view the contents.
The path points at a non-directory file.
let paths = fs::read_dir("./a").unwrap();
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:4:35
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
In Rust, there are 2 ways to raise a number to a power.
Using pow Method
The pow() function raises a value to the power of exp, using exponentiation by squaring. Note that 0⁰ (pow(0, 0)) returns 1. Mathematically this is undefined.
See the following example:
fn main() {
let base: i32 = 2;
println!("{}", base.pow(10));
}
1024
Using i32::pow Method
Here is the simplest method which you can use:
fn main() {
let a = 2;
println!("{}", i32::pow(a, 10));
let b = 2;
println!("{}", u32::pow(b, 8));
// For floats:
println!("{}", f32::powf(2.0, 10.0));
}
1024
256
1024
In Golang, using the strings.EqualFold function is the easiest way to check if two strings are equal in a case-insensitive manner
Using strings.EqualFold Function
The strings.EqualFold() function reports whether s and t, interpreted as UTF-8 strings, are equal under Unicode case-folding, which is a more general form of case-insensitivity.
See the following example:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.EqualFold("HeLLO", "hello"))
// It even works with Unicode.
fmt.Println(strings.EqualFold("A̐É", "a̐é"))
}
true
true
In Golang, there are 2 ways to get the difference in hours between two dates.
Using time.Since Function
The time.Since() function returns the time elapsed since t. It is shorthand for time.Now().Sub(t). For example,
package main
import (
"fmt"
"time"
)
func main() {
layout := "2006-01-02 15:04"
v := "2022-05-09 10:00"
t, err := time.Parse(layout, v)
if err != nil {
// panic()
}
duration := time.Since(t)
fmt.Println(duration.Hours())
}
-2.5214217017602776
Using Sub Function
The Time.Sub() function returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).
package main
import (
"fmt"
"time"
)
func main() {
layout := "2006-01-02 15:04"
v := "2022-05-09 10:00"
t, err := time.Parse(layout, v)
if err != nil {
// panic()
}
v = "2022-05-09 05:23"
t2, err := time.Parse(layout, v)
if err != nil {
// panic()
}
duration := t2.Sub(t)
fmt.Println(duration.Hours())
}
-4.616666666666667
In Golang, there are 2 ways to validate URL with standard package.
Using ParseRequestURI Function
url.ParseRequestURI parses a raw url into a URL structure. It assumes that url was received in an HTTP request, so the url is interpreted only as an absolute URI or an absolute path. The string url is assumed not to have a #fragment suffix.
See the following example:
package main
import (
"fmt"
"net/url"
)
func main() {
s := "http//google.com"
_, err := url.ParseRequestURI(s)
if err != nil {
// invalid
fmt.Println(err)
}
}
parse "http//google.com": invalid URI for request
Using Parse Function
The url.Parse() function parses a raw url into a URL structure. For example,
package main
import (
"fmt"
"net/url"
)
func IsUrl(str string) bool {
u, err := url.Parse(str)
return err == nil && u.Scheme != "" && u.Host != ""
}
func main() {
s := "http//google.com"
fmt.Println(IsUrl(s))
}
false
In Golang, using the NumCPU function is the easiest way to find out the number of CPU's on a local machine.
Using runtime.NumCPU Function
The runtime.NumCPU() method returns the number of logical CPUs usable by the current process.
The set of available CPUs is checked by querying the operating system at process startup. Changes to operating system CPU allocation after process startup are not reflected.
See the following example:
package main
import (
"fmt"
"runtime"
)
func main() {
cpus := runtime.NumCPU()
fmt.Println(cpus)
}
4
In Golang, using the unsafe.Sizeof function is the easiest way to get memory size of the variable
Using Sizeof Function
You can use the unsafe.Sizeof function for this. It returns the size in bytes.
See the following example:
package main
import (
"fmt"
"unsafe"
)
func main() {
a := 10
s := "Hello World"
fmt.Printf("%d\n", unsafe.Sizeof(a))
fmt.Printf("%d, len: %d\n", unsafe.Sizeof(s), len(s))
}
8
16, len: 11
In Golang, using the cases package is the easiest way to make first letter of words uppercase in a string.
Using cases Package
install
Use the following command to download the repository to the local file system.
install
go mod tidy
go get golang.org/x/text/cases
go get golang.org/x/text/language
go install golang.org/x/text/cases@latest
go install golang.org/x/text/language@latest
Note that since Go 1.17 installing packages with go get is deprecated:
cases Usage
Package cases provides general and language-specific case mappers.
See the following example:
package main
import (
"fmt"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func main() {
s := "hello world!"
for _, c := range []cases.Caser{
cases.Title(language.Dutch),
cases.Title(language.Und, cases.NoLower),
} {
fmt.Println(c.String(s))
}
}
Hello World!
Hello World!
In Golang, there are 2 ways to pipe several commands.
Using piped commands
For example, this function retrieves the CPU model name using piped commands:
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := "cat /proc/cpuinfo | egrep '^model name' | uniq | awk '{print substr($0, index($0,$4))}'"
o, err := exec.Command("bash", "-c", cmd).Output()
if err != nil {
// log.Fatal
}
fmt.Println(string(o))
}
Intel(R) Core(TM) i5 CPU M 460 @ 2.53GHz
Using StdoutPipe
StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts. The pipe will be closed automatically after Wait sees the command exit.
package main
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
)
func main() {
c1 := exec.Command("ls")
c2 := exec.Command("wc", "-l")
r, w := io.Pipe()
c1.Stdout = w
c2.Stdin = r
var b2 bytes.Buffer
c2.Stdout = &b2
c1.Start()
c2.Start()
c1.Wait()
w.Close()
c2.Wait()
io.Copy(os.Stdout, &b2)
fmt.Println(b2.String())
}
6
In Golang, there are 2 ways to copy a file.
Using io.Copy Function
You can copy a file using the io.Copy() function. For example,
package main
import (
"io"
"os"
)
// Copy the src file to dst.
func Copy(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
_, err = io.Copy(out, in)
if err != nil {
return err
}
return nil
}
func main() {
Copy("access.log", "access.1.log")
}
access.1.log
Using ioutil.WriteFile Function
The following example should cover whatever you are trying to do:
package main
import (
"io/ioutil"
)
// Copy the src file to dst.
func Copy(src, dst string) error {
data, err := ioutil.ReadFile(src)
if err != nil {
return err
}
err = ioutil.WriteFile(dst, data, 0644)
if err != nil {
return err
}
return nil
}
func main() {
Copy("access.log", "access.1.log")
}
access.1.log
In Python, using the uuid module is the easiest way to create a GUID/UUID.
Using uuid Module
uuid module provides immutable UUID objects (the UUID class) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122.
See the following example:
#!/usr/bin/python3
# Import module
import uuid
print(uuid.uuid4())
# a 32-character hexadecimal string
print(uuid.uuid4().hex)
a41324c5-fff7-48c8-b7a5-75b4ed877ad9
9606b3e9a271426e8790d72cd90882a4
In Python, using the timedelta object is the easiest way to subtract a day from a date.
Using timedelta Object
A timedelta object represents a duration, the difference between two dates or times.
See the following example:
#!/usr/bin/python3
# Import module
import datetime
t = datetime.datetime.today()
d = t - datetime.timedelta(days=1)
print(t)
print(d)
2022-05-08 21:06:31.549667
2022-05-07 21:06:31.549667
Syntax
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.
In Python, there are 3 ways to remove all whitespace in a string.
Using str.replace Function
The str.replace(x) function returns a copy of the string with all occurrences of substring old replaced by new.
See the following example:
#!/usr/bin/python3
s = " \nHello World "
n = s.replace(" ", "")
print('{!r}'.format(n))
'\nHelloWorld'
Using str.split Method
If you want to remove spaces, use str.split() followed by str.join():
#!/usr/bin/python3
s = " \nHello World "
n = ''.join(s.split())
print('{!r}'.format(n))
'HelloWorld'
Using regular Expression
To remove all whitespace characters (space, tab, newline, and so on) you can use a regular expression:
#!/usr/bin/python3
# Import module
import re
s = " \nHello World "
n = re.sub(r"\s+", "", s, flags=re.UNICODE)
print('{!r}'.format(n))
'HelloWorld'
In Python, there are 3 ways to delete a list element by value.
Using list.remove Function
The list.remove(x) function removes the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
See the following example:
#!/usr/bin/python3
l = ["a", "c", "b", "c"]
if 'c' in l:
l.remove("c")
print(l)
# try:
# l.remove('c')
# except ValueError:
# pass
['a', 'b', 'c']
Using List Comprehension
To remove all occurrences of an element, use a list comprehension:
#!/usr/bin/python3
l = ["a", "c", "b", "c"]
l = [x for x in l if x != 'c']
print(l)
['a', 'b']
Using filter Function
To take out all occurrences, you could use the filter function in python. For example, it would look like:
#!/usr/bin/python3
l = ["a", "c", "b", "c"]
l = list(filter(lambda x: x != 'c', l))
print(l)
['a', 'b']
Python Errors
ValueError:
# ...
l.remove("e")
l.remove("e")
ValueError: list.remove(x): x not in list
In Python, there are 3 ways to return dictionary keys as a list.
Using keys Function
The dict.keys() function returns a view object that displays a list of all the keys in the dictionary in order of insertion.
See the following example:
#!/usr/bin/python3
d = {"a": 1, "c": 2, "b": 3}
keys = list(d.keys())
print(keys)
['a', 'c', 'b']
Using Unpacking
New unpacking generalizations (PEP 448) were introduced with Python 3.5 allowing you to now easily do:
#!/usr/bin/python3
d = {"a": 1, "c": 2, "b": 3}
# Python >= 3.5
keys = [*d]
print(keys)
['a', 'c', 'b']
Using Extended Iterable Unpacking
The following example should cover whatever you are trying to do:
#!/usr/bin/python3
d = {"a": 1, "c": 2, "b": 3}
# Python >= 3.x
*keys, = d
print(keys)
['a', 'c', 'b']
In Python, there are 3 ways to get file creation and modification dates times.
Using os.path Function
The os.path.getmtime() function returns the time of last modification of path.
The os.path.getctime() function returns the system’s ctime which, on some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path.
Here is an example code:
#!/usr/bin/python3
# Import module
import os.path, time
f = "file.txt"
print(time.ctime(os.path.getatime(f)))
print(time.ctime(os.path.getmtime(f)))
print(time.ctime(os.path.getctime(f)))
Sat May 7 17:33:53 2022
Sat May 7 17:33:53 2022
Sun May 8 09:27:51 2022
Using os.stat Function
Get the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. p
You can use os.stat() function, it really simple. For example,
#!/usr/bin/python3
# Import module
import os, time
f = "file.txt"
stat = os.stat(f)
print(time.ctime(stat.st_atime))
print(time.ctime(stat.st_mtime))
print(time.ctime(stat.st_ctime))
Sat May 7 17:33:53 2022
Sat May 7 17:33:53 2022
Sun May 8 09:27:51 2022
Using pathlib Module
you can use the object oriented pathlib module interface which includes wrappers for much of the os module. Here is an example of getting the file stats.
#!/usr/bin/python3
# Import module
import pathlib, time
f = "file.txt"
p = pathlib.Path(f)
stat = p.stat()
print(time.ctime(stat.st_atime))
print(time.ctime(stat.st_mtime))
print(time.ctime(stat.st_ctime))
Sat May 7 17:33:53 2022
Sat May 7 17:33:53 2022
Sun May 8 09:27:51 2022
Python Errors
FileNotFoundError:
f = "file.tx"
# ...
stat = p.stat()
return self._accessor.stat(self, follow_symlinks=follow_symlinks)
FileNotFoundError: [Errno 2] No such file or directory: 'file.tx'
In Python, using the ord function is the easiest way to get the ASCII value of a character as an int.
Using ord Function
The ord() function returns an integer representing the Unicode code point of that character.
To get the ASCII code of a character, you can use the ord() function.
Here is an example code:
#!/usr/bin/python3
print(ord('a'))
print(ord('€'))
# inverse
print(chr(97))
97
8364
a
In Python, there are 3 ways to check if a variable exists.
Using locals Function
The locals() function returns the dictionary of the current local symbol table.
#!/usr/bin/python3
vName = 1
if 'vName' in locals():
print("exists")
exists
Using globals Function
The globals() function returns the dictionary of the current global symbol table.
#!/usr/bin/python3
vName = 1
if 'vName' in global():
print("exists")
exists
Using hasattr Method
To check if an object has an attribute:
#!/usr/bin/python3
class Person:
name = 'Ada'
person = Person()
if hasattr(person, 'name'):
print("exists")
exists
In Python, there are 4 ways to copy a dictionary.
Using dict Method
If you want to copy the dict, you have to do so explicitly with:
#!/usr/bin/python3
a = {"a": 1, "b": 2}
# Copy
b = dict(a)
b['a'] = 3
print(a)
print(b)
{'a': 1, 'b': 2}
{'a': 3, 'b': 2}
Using dict.copy Method
The copy() method returns a copy of the dictionary.
#!/usr/bin/python3
a = {"a": 1, "b": 2}
# Copy
b = a.copy()
print(b)
{'a': 1, 'b': 2}
Using copy Module
The copy.deepcopy() method returns a deep copy of x.
#!/usr/bin/python3
# Import module
import copy
a = {"a": 1, "b": 2}
# Copy
b = copy.deepcopy(a)
print(b)
{'a': 1, 'b': 2}
Using ** Unpackaging Operator
On python 3.5+ there is an easier way to achieve a shallow copy by using the ** unpackaging operator. Defined by Pep 448.
#!/usr/bin/python3
a = {"a": 1, "b": 2}
# Copy
b = {**a}
print(b)
{'a': 1, 'b': 2}
In Python, there are 3 ways to move a file.
Using os Module
The os.rename() method renames the file or directory src to dst. If dst exists, the operation will fail with an OSError subclass in a number of cases:
#!/usr/bin/python3
# Import module
import os
os.rename("file.txt", "file.1.txt")
os.replace("file.1.txt", "file.txt")
file.1.txt
Using shutil.move Method
Recursively move a file or directory (src) to another location (dst) and return the destination.
#!/usr/bin/python3
# Import module
import shutil
shutil.move("file.txt", "file.1.txt")
file.1.txt
Using pathlib Module
After Python 3.4, you can also use pathlib's class Path to move file.
#!/usr/bin/python3
# Import module
import pathlib
pathlib.Path("file.txt").rename("file.1.txt")
file.1.txt
In Python, there are 2 ways to determine if an object is iterable.
Using Duck Typing
Duck typing is a concept related to dynamic typing, where the type or the class of an object is less important than the methods it defines. When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute.
See the following example:
#!/usr/bin/python3
a = "abcd"
try:
i = iter(a)
print("Iterable")
except TypeError:
print("Not Iterable")
a = 1
try:
i = iter(a)
print("Iterable")
except TypeError:
print("Not Iterable")
Iterable
Not Iterable
Using Type Checking
Use the Abstract Base Classes. They need at least Python 2.6 and work only for new-style classes. For example,
#!/usr/bin/python3
# Import module
from collections.abc import Iterable
a = 1
print(isinstance(a, Iterable))
a = "1"
print(isinstance(a, Iterable))
False
True