Q:

How to write a script / library within the same file?

I want to implement certain functionality using python that can be used in two ways: 

as simple command line script, like python mylib.py
by importing into other python code

My first attempts look like this.
mylib.py:
from __future__ import print_function
import sys

class A(object):
    def __init__(self, args):
        print("my args: {}".format(args))

def main():
    a = A(sys.argv)
    print("got {}".format(a))

main()

Which I can directly invoke, or use elsewhere, like usage.py:
import mylib

mylib.A("bla")

That works, but it seems the import causes main() to be executed as well:
python scripts/using.py blub
my args: ['scripts/using.py', 'blub']
got <mylib.A object at 0x7ff17bc736d0>
my args: bla

Questions:

Is there a way to prevent main() from running when I go for python using.pl?

And beyond that:

Is this a good approach? Or are there well established best practices in python that I am violating here?
In other words: are there things I should do differently?

A:

Since @CoryKramer has already answered the first part of the question, let me take a shot at the second part.
Code should exists where it belongs. If it has anything to do with parsing the script or the main execution, then it should be in the script. Any other piece of code shouldn't be the part of script file.
Generally, in production code, you should never import from a script file. The common code should exist in it's own class in a separate file or just in a separate file in case of procedural approach. This way the code in your script would be succinct and the code in the common file is reusable in other production code and you won't run a risk of accidentally executing a script, just to use the common code.
# common.py
class A(object):
    def __init__(self, args):
         print("my args: {}".format(args))

# mylib.py
from common import A

if __name__ == '__main__':
    a = A(sys.argv)
    print("got {}".format(a))

