Why Python Doesn't Import All Libraries Like In Java

Do you like this?

Summary:
When I just started to learn Python, I was wondering why other Pythonists don't put all the import statements right at the beginning of the Python files as in Java which in my mind was much clearer and more structured. Since my background was from Java and moved to Python by jumping into Django, it took me some time to realise this. However, I'm not saying this is totally right. It's basically just my take after doing a number of projects in Python and Django. Hence, you're welcome to comment and give your own thoughts on this.


Content:

Following is the source code for the Date class whose methods and details have been taken out because we are more interested only in the import statements.

package java.util;

import java.text.DateFormat;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.lang.ref.SoftReference;
import sun.util.calendar.BaseCalendar;
import sun.util.calendar.CalendarDate;
import sun.util.calendar.CalendarSystem;
import sun.util.calendar.CalendarUtils;
import sun.util.calendar.Era;
import sun.util.calendar.Gregorian;
import sun.util.calendar.ZoneInfo;

public class Date
	implements java.io.Serializable, Cloneable, Comparable
{
	// code was removed from here
	
	public Date() {
		this(System.currentTimeMillis());
	}

	// other calculations and methods were here
}


As you can see, all the import statements are declared right from the beginning whereas in Python code, it's not always the case. For example, following is a piece of code to demonstrate this.
def total(x,y):
	return x+y
	
def tomorrow():
	from datetime import datetime, timedelta
	tmr = datetime.today() + timedelta(days=1)
	return tmr.strftime("%Y-%m-%d")
	
def current_path():
	import os.path
	return os.path.realpath(__file__)
Let's save the Python file as functions.py. Apparently, if you call an import module for the file functions.py: import functions, you can call any of the functions written in there. You can also reuse this file as many times as you wish to. The key thing is that not all the import statements will be executed every time you call import functions. Depending upon the methods being called, the corresponding import statements such as import os.path will be executed.

On the other hand, when you compile a Java file, all the import statements have to be declared at the beginning and must be accurate. Does it mean Java is less robust? Not really. Even though in Java, you have to declare all the import statements at the beginning, at run time, Java Runtime Environment (JRE) might not execute all the import statements. They are required to be there but only for the purpose of safe type checking. In other words, after you compile Java source code, you can remove Java classes from the Java Path, and your program will still be running perfectly without giving any errors as long as in the current code, no calling to the methods in the removed Java classes takes place.

In the case of Python, suppose you have 2 files - print_path.py and test.py as below:
######### print_path.py #########

def current_path():
	import os.path
	return os.path.realpath(__file__)
	
print current_path()



and
######### test.py #########

import print_path



Now if you run this command in the console for executing the test.py: python test.py. What you are going to get is the print result from the file print_path.py which is the directory path to that file. However, in Java, you can't see this effect because every Java file is a class which composes of attributes and methods. Without a specific method invoking to a method, the method will not be executed. Let's take a look at a simplified Java class below.

public class Robot {

	private String name;
	
	public Robot(String name){
		this.name= name;
		System.out.println("A new Robot["+name+"] object is created");
	}

	public void fight(){
		System.out.println("Robot["+name+"] is fighting");
	}

}

Now you might be wondering how the method fight() can take place. It can be invoked either by another method from another class or by itself. I'm not going to discuss how other Java classes can invoke this fight() method because it's out of our topic today. But I can show you how to invoke the fight() method by the Robot class itself.

public class Robot {

	private String name;
	
	public Robot(String name){
		this.name= name;
		System.out.println("A new Robot["+name+"] object is created");
	}

	public void fight(){
		System.out.println("Robot["+name+"] is fighting");
	}
	
	
	public static void main(String[] args){
		Robot r = new Robot("Wilson");
		r.fight();
		//the result is:
		//A new Robot[Wilson] object is created
		//Robot[Wilson] is fighting
	}
	
}

Then what you need to firstly compile the Java file into bytecode then execute the file with this command: java Robot

What I'm trying to say here is that Java purely works on the concept of Object-Oriented whereas Python can be used for both Object-Oriented or scripting with functions and procedures. Again, coming back to our point, as discussed Python files can include unrelated functions so it can have specific import statements in each functions. For Java, every file is a class with related attributes and methods so all the import statements must be explicitly declared at the top.

 
comments powered by Disqus