Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a general question
#1
I have the following code, the first method, SendCommandV1, was given to me. My question is do I have to pass ser as an argument when I call SendCommand? Since ser is defined globally, I do not see any reason to pass ser through the argument.
Would the second method, SendCommandV2 be just as good?


ser = serial.serial('COM3', '9600')

def SendCommandV1(ser, command_string):
   ser.write(command_string)

def SendCommandV2(command_string):
   ser.write(command_string)

SendCommandV1('ser, Hello World')
SendCommandV2('Hello World')  #is this OK?
Reply
#2
You are calling SendCommandV1 incorrectly. It should be:
SendCommandV1(ser, 'Hello World')
You can write SendCommandV2(cmd) as you have, but SendCommandV1(port, cmd) is better. In general functions that use arguments are better than functions that use global variables. If you wanted to modify your program to write to two serial ports you would need to make a duplicate SendCommandV2() that is identical to the original except it writes to a different serial port. SendCommandV1() does not have to be changed to work with any number of serial ports. There are other compelling reasons to avoid using global variables in functions that I'm not going into here. If you are interested you can google "why are python global variables bad".
Reply
#3
You can also use functools.partial() to intern some arguments
from functools import partial
ser = serial.serial('COM3', '9600')
 
def SendCommandV1(ser, command_string):
   ser.write(command_string)

SendCommandV2 = partial(SendCommandV1, ser)

SendCommandV2('Hello world')
Reply
#4
Ok first I convert this code to pep8 style guide.
ser = serial.serial('COM3', '9600')
 
def SendCommandV1(ser, command_string):
   ser.write(command_string)
 
def SendCommandV2(command_string):
   ser.write(command_string)
 
SendCommandV1('ser, Hello World')
SendCommandV2('Hello World')  #is this OK?
To this:
from serial import Serial
# Serial is a class

# Functions: lower_case_whitespace_by_underscore
# Function are verbs, so send_command is a good choice
def send_command_v1(serial_connection, command_string):
   serial.write(serial_connection)

# bad example. this function fails, if you use
# it in another module and forgot, that you don't
# have ser
def send_command_v2(command_string):
   ser.write(command_string)
 
# there was a quote before ser, this was wrong
# use double quotes where you can. Why? You can see them better
# A IDE can also help to see the difference with syntax highlighting

# ser was too far away from usage
ser = Serial("COM3", 9600)
# baudrate, the 2nd parameter, should be an int and not  a str

send_command_v1(ser, "Hello World")
If this is a throw away script, it's too complicated.
from serial import Serial


with Serial('COM3', 9600) as ser:
    ser.write("Hello World")
A function which just pass through a string to a method is not very useful.
If this function does send a predefined command, then it's useful.

def send_shutdown(serial_connection):
    serial_connection.write(b"SHUTDOWN\n")
If you don't like to pass through always the serial_connection object, then object-oriented programming is the solution.

#!/usr/bin/env python3
# for windows users this shebang is useless
# for *nix (linux, mac, bsd) it's common to have a shebang

from serial import Serial


class SerialCommander:
    """
    The SerialCommander can send greet and shutdown.
    """

    def __init__(self, port, baudrate):
        """
        Connect to a serial port with given baud rate.
        On Windows systems, use: COM3 or COM4
        On Linux Systems there are different variations
        """
        self.connection = Serial(port, baudrate)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # if an exception happened in the with-block,
        # then the arguments have a meaing.
        # we use it just to close the connection
        self.connection.close()

    def greet(self):
        self.connection.write(b"Hello World\n")

    def shutdown(self):
        self.connection.write(b"SHUTDOWN\n")


def main()
    """
    Main program
    """

    # SerialCommander(...) calls __init__ and an instance is returned
    # then with calls __enter__ which just returns self, which is the same object
    # this returned instance is assigned to commander
    with SerialCommander("COM4", 9600) as commander:
        # calling methods on SerialCommander instance
        # commander is the name, where the created instance (object) points to
        commander.greet()
        commander.shutdown()
    # leaving the with block, calls __enter__ of the instance commander


# calls main only if this module was not imported
# it's only called, if you run this as a script
if __name__ == "__main__":
    main()
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
Dean, I understand what you are saying.

Gribou, could I also do this...
ser = serial.serial('COM3', '9600')
  
def SendCommandV1(ser, command_string):
   ser.write(command_string)

def SendCommandV2(command_string)
   SendCommandV1(ser, command_string)

SendCommandV2('Hello World')
Reply
#6
You can also do
SendCommandV3 = ser.write
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python can - general question caslor 0 1,125 Jul-14-2022, 05:21 PM
Last Post: caslor
  General Programming Question with Dictionary giddyhead 12 2,746 Jan-10-2022, 10:12 AM
Last Post: Pedroski55
Big Grin General programming question (input string)[ jamie_01 2 1,608 Jan-08-2022, 12:59 AM
Last Post: BashBedlam
  Question about formula implementation in general format Alienspecimen 0 1,669 Mar-01-2021, 08:39 PM
Last Post: Alienspecimen
  General list size question to solve problem Milfredo 3 2,369 Sep-27-2020, 08:42 AM
Last Post: Milfredo
  General Listbox question. Milfredo 4 2,164 Sep-06-2020, 07:36 PM
Last Post: Milfredo
  General question about serialization/deserialization in python local 1 1,853 Jan-28-2020, 04:35 AM
Last Post: Larz60+
  General Programming Question Qui_Ten 1 2,195 Jan-14-2019, 11:15 AM
Last Post: steve_shambles

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020