'How to simplify Import

How to simplify this to be more small

from tkinter import *
from random import randint
from tkinter import ttk
import tkinter as tk
import random, os

Thanks



Solution 1:[1]

Only import them,

import tkinter as tk
import random
import os

then use in code like this,

random.randint

tk.ttk

Updated

But according to best practice use this

import os
from tkinter import ttk
from random import randint

Solution 2:[2]

  1. Keep only one for random, one for tkinter

  2. for each choose :

    • from PACKAGE import STUFF1, STUFF2 : there is not so much imports, and name are easily understandable
    • import PACKAGE as p : there is many imports to do from, or import name can be confusing
  3. NEVER USE *, always explicit names

  4. Follow community "rules", for mainstream packages

    import pandas as pd
    import numpy as np
    

Solution 3:[3]

constructing on @SAM's answer, you can further reduce a line of code like this:

import tkinter as tk
import random, os

If you want to further make it a 1-liner, then you must perform blasphemy in python: the semicolon

import tkinter as tk; import random, os

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Ishan J.