Create a main in python

Defining a main function in Python

Sign in to your Python Morsels account to save your screencast settings.

Let’s talk about creating a main function in Python.

Many programming languages have the notion of a main function (or a main method), which acts as the entry point for a program. Python does not have main functions.

Python runs all code in Python scripts

We have a Python script called greet.py :

import random salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"] def greet(): """Print a salutation.""" print(random.choice(salutations)) greet() 

When we run greet.py from our system command-line, Python runs all of the code in this file:

But what if we import this Python file?

Python runs all code in Python modules

If we import our greet module, Python also runs all of the code in our file:

We’re seeing «Hey» printed out at import time because Python ran our greet function (which we called at the bottom of our module):

It’s very weird to see something printed out when we just import a module. But that’s just what Python does: Python runs all code in a module on import .

This greet.py file wasn’t actually meant to be used as a module. This file wasn’t meant to be imported; it was meant to be run as a script.

Using the same Python file as both a module and a script

What if we wanted to make one .py file that could both be imported as a module and could be used as a Python script (by being run from the command-line)?

This version of our greet.py file can be run as a program to print out a random greeting:

$ python3 greet.py Howdy $ python3 greet.py Hiya 

But if we import it as a module, it doesn’t do anything (except give us access to functions and whatever else is in that module):

>>> import greet >>> greet.greet() Hiya 

How is this possible in Python?

Python’s if __name__ == «__main__» check

It turns out there’s a way to ask, are we being run from the command-line. Or put another way, is our current Python module the entry point to our Python process? This question can be asked using the statement __name__ == «__main__» .

This version of greet.py works as both a command-line script and an import-able module:

import random salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"] def greet(): """Print a salutation.""" print(random.choice(salutations)) if __name__ == "__main__": greet() 

Every module has a __name__ variable, and by default the __name__ variable in each module is a string representing the name of that module:

>>> import greet >>> greet.__name__ 'greet' 

That’s the case if we’re importing a module.

Читайте также:  List file method in java

But what if we run that our greet.py file from the command-line?

In that case, __name__ is not going to be the name of that module. Instead, it’s going to be «__main__» . That’s why running greet.py also runs the greet function:

This block of code is really asking the question are we the entry point to our Python program (are we being run from the command-line rather than being imported as a module)?

if __name__ == "__main__": greet() 

If we are being run from the command-line then we run our greet function.

You can write a main function, but you don’t need to

You may sometimes see Python programs that have a main function:

import random salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"] def main(): """Print a salutation.""" print(random.choice(salutations)) if __name__ == "__main__": main() 

Python doesn’t know about main functions, but there’s nothing stopping us from making a function called main that we only call if we’re being run from the command-line.

Remember that if __name__ == «__main__» incantation

If you need to make a single Python file that can both be used as a module (being imported) and can be run as a Python script to do something, you can check the variable __name__ in your module to see whether it’s equal to the string «__main__» .

What comes after Intro to Python?

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I’ll explain concepts that new Python programmers often overlook.

Series: Command-Line Programs

A .py file can be used as a module or as a «script» which is run from your operating system’s command-line/terminal. Python is a great programming language for making command-line scripts.

To track your progress on this Python Morsels topic trail, sign in or sign up.

Источник

How Do You Write a Main Function in Python?

If you are just starting with Python, you might not be aware yet of the best practice of defining functions. In this guide, I’ll explain how including a main() function, though not required in Python, can structure your programs in a logical way and ensure that your functions are executed only when expected.

The Python ecosystem is very rich in modules, packages, libraries, and frameworks. It is sometimes challenging for beginners to understand the difference between these concepts, but basically they’re all forms of organizing Python code.

For example, a module is a bunch of related code saved in a file with the extension .py. With a custom module in Python, you can define variables, functions, or even create your own classes. You can include runnable code in modules. However, if a module with runnable code is imported from a different module, this code would execute itself when it is imported.

In this article, I’ll discuss how to avoid this situation by adhering to the Python best practice of separating code that should be executed only when it is run as a script (but not when it’s imported).

After you read this guide, I encourage you to start practicing right away with the interactive learning track Learn Programming with Python. It includes hundreds of coding challenges covering this language’s basics as well as more advanced concepts for writing optimized Python applications.

Читайте также:  Php class this in method

Python Top-level Code Environment

Module objects in Python are characterized by various attributes that are prefixed and postfixed by a double underscore (‘__’). The key attribute of each module is its name – or more precisely, __name__ .

In any module you import, its name will be set to the name of the file. For example, if you import the NumPy module, you’ll see that its attribute __name__ will be equal to numpy :

>>> import numpy >>> print(numpy.__name__)

The important thing to remember is that when Python is running as a top-level executable code (i.e. when read from standard input, a script, or an interactive prompt), the __name__ attribute is set to ‘ __main__ ‘. So, we can literally say that, in the top-level script environment, __name__ = ‘__main__’ .

Why not use this knowledge to separate the code in your module that is intended for script use only? Good coding practices suggest using the following if code block …

.. and including there the code that we only want to run when the module is executed in the top-level environment.

Let’s see how this works with a few examples.

Good Practices of Organizing Code When Defining a Function

We’ll start with a basic example to demonstrate how you can separate executable code in your module. Then, we’ll move to a more complex example, where we’ll define a main() function.

Example 1. Separating executable code

Let’s say we are developing a game that only people aged 18+ are allowed to play. The age variable is declared in the top-level environment by getting input from the user:

# Declare global variable age age = int(input('Please enter your age in years: '))

Then, we have a called module age_check.py that has the following code:

# Define a function to check that age is 18+ def age_check(age): if age >= 18: print('You are allowed to enter the game.') else: print('You are not allowed to enter the game.') # Execute age_check() function age_check(age)

As you see, this module has an executable piece of code after the age_check() function is defined. Hence if we import age_check.py , its code will be run automatically. To avoid this, you can put the executable code separately in the if __name__ == ‘__main__’ code block:

# Define a function to check that age is 18+ def age_check(age): if age >= 18: print('You are allowed to enter the game.') else: print('Unfortunately, you are not allowed to enter the game because of the age restriction.') #Execute age_check() function if __name__ == '__main__': age_check(age)

In such a case, you can import the age_check() module without the runnable code being executed. Everything within the if __name__ == ‘__main__’ block won’t run unless the module is executed in the top-level environment.

Example 2. Defining the main function in Python

In our first example, I’ve demonstrated the key principle of how we can separate executable code so that it runs only when executed in the top-level environment. However, in practice, modules often define many different variables, functions, and classes. You may also have several unrelated pieces of runnable code within one module. So, to improve code clarity and correctness, it’s a best practice to put as few statements as possible in the block below if __name___ == ‘__main__’ . Most often, a function named main() encapsulates the program’s primary behavior.

Читайте также:  Javascript вывести содержимое файла

For example, let’s say we want to write a Python module that greets new members and checks their age. First, we have the name and age variables declared in the top-level code environment:

name = str(input('Please enter your name: ')) age = int(input('Please enter your age in years: '))

Then, we can have the following welcome.py module imported:

# Define a function to greet new players def greeting(name): print ("Hi <>. Glad to see you here.".format(name)) # Define a function to check that age is 18+ def age_check(age): if age >= 18: print('You are allowed to enter the game.') else: print('Unfortunately, you are not allowed to enter the game because of the age restrictions.') # Define main function def main(): greeting(name) age_check(age) # Execute main() function if __name__ == '__main__': main()

As you see, we first define two separate functions to greet new players and to check their age. Next, we define the main() function, which contains a call to the greeting() and age_check() functions. Finally, we add the if __name__ == ‘__main__’ : code block at the end of the file.

Since we have all the functions we would like to run in the main() function, we only call the main() function following this if statement. Since all the runnable code is placed under the if statement, it will not be executed during the module import.

Of course, you can always choose NOT to declare a main() function and have the following code block instead:

if __name__ == '__main__': greeting(name) age_check(age)

However, best practices suggest using the main() function. Defining the main function in Python and then using it in the if __name__ == ‘__main__’ : statement allows you to organize your code logically and make it more readable and easier to follow. This would be particularly obvious with complex modules that define several functions and/or classes.

You might be also interested in making your code more professional and cleaner-looking with our guide to the argparse module.

Time to Practice Main Functions in Python!

To master any new skill, you need lots of practice. When it comes to practicing Python, I think interactive online courses are the best option for beginners. With a good course, you have all the coding examples prepared for you. Hence, you can focus on the new concepts you’re learning, without the need to set up a Python coding environment and search for projects to practice.

For aspiring Python programmers, I recommend our interactive learning track Learn Programming with Python. It includes five courses covering the very basics (defining variables, writing conditional statements and loops, etc.), more advanced concepts, and advice on best coding practices.

Thanks for reading, and happy learning!

Bonus. Here’s the list of the most popular Python packages.

Источник

Оцените статью